<?php
require_once("page.class.php");
require_once("functions.php");
require_once("adrese.class.php");
require_once("komitent.core.class.php");
require_once("adresaTemplate_string.php");

define("SEARCH_LIMIT",50);
define("PAGE_LENGTH",20);

class komitenti extends komitentObject{
	var $db;		// db_functions object
	var $adrese;	// adrese object;
	var $tables = array(
		'root' => "komitenti",
		'tipovi' => "komitenti_tipovi",
		'telefoni' => "komitenti_del_telefoni",
		'delatnosti' => "komitenti_delatnosti",
		'kampanje' => "komitenti_kampanje",
		'radnici' => "komitenti_radnici",
		'strukture' => "komitenti_strukture",
		'ziro' => "komitenti_ziro_racuni"
		);
	var $komitentAttributes = array(
			"1"=>"telefon",
			"2"=>"fax",
			"3"=>"web",
			"4"=>"e-mail",
			"5"=>"žiro račun"
		);
	var $mesta_skracenice = array(
		45 => "Bg",		// Beograd
		199=> "N.Bg"	// Novi Beograd
	);
	
	var $listingTXTRowDelimiter = "%#%";
	var $listingStyleDelimiter = "#";
	
	function komitenti($get="",$post=""){
		if(!$this->isUserLoggedIn()){
			header("Location: index.php");
		}
		$this->initPage();
		$this->db = new db_functions();
		$this->adrese = new adrese();
		$action = strlen($get['a'])?$get["a"]:$post["a"];
		$mod = getFromInput("mod");
		switch($action){
			case "materijal":
				switch ($mod){
					case "new":
						$this->MaterijalSendNew();
						break;
					case "save":
						$this->MaterijalSendSave();
						break;
					case "delete":
						$this->MaterijalSendDelete();
						break;
					default:
						$this->MaterijalSendView();
						break;
				}
				break;
			case "yapyap":
				switch ($mod){
					case "add":
						$this->yapyapAdd();
						break;
					case "del":
						$this->yapyapDelete();
						break;
					default:
						$this->yapyap();
						break;
				}
				break;
			case 'yapfox':
				$this->yapfox();
				break;
			case "listing":
				switch ($mod){
					case "bind":
						$this->listingBind();
						break;
					case "makeTXT":
						$this->listingMakeTXT();
						break;
					case "settings":
						$this->listingSettings();
						break;
					case "saveSettings":
						$this->listingSettingsSave();
						break;
					case "ukupno":
						$this->listingDelatnostiUkupno();
						break;
					default:
						$this->listingDelatnosti();
						break;
				}
				break;
			case "listingBusiness":
				switch ($mod){
					default:
						$this->listingBusiness();
						break;
				}
				break;
			case "getUgovori":
				$this->getUgovori();
				break;
			case "wwwdata":
				$this->wwwData();
				break;
			case 'new':
				$this->displayNew();
				break;
			case 'del':
				$this->delKomitent($get["id"]);
				break;
			case 'newAdd':
				$this->addNew($get["data"]);
				break;
			case 'newDelHTML':
				$this->generateNewDelHTML($get["id"]);
				break;
			case 'save':
				$this->save($post["data"]);
				break;
			case 'types';
				$this->displayTypes();
				break;
			case 'newType';
				$t = $_GET["t"];
				if($t == "type")
					echo $this->parseTemplate("komitenti/new/new_type.tpl");
				elseif($t == "struct")
					echo $this->parseTemplate("komitenti/new/new_struct.tpl");
				break;
			case 'addNewType':
				$t = $_GET["t"];
				if($t == "type"){
					$this->addType("type",$_GET['name']);
				}elseif($t == "struct"){
					$this->addType("struct",$_GET['name']);
				}				
				break;
			case 'delType':
				$this->deleteTypes($get['id'],$this->tables["tipovi"],"kom_tip_id");
				break;
			case 'editType':
				$this->editType($get['id']);
				break;
			case 'updateTypes':
				$this->updateTypes($get["pars"]);
				break;
			case 'struct';
				$this->displayStructs();
				break;
			case 'editStruct':
				$this->editStruct($get['id']);
				break;
			case 'updateStructs':
				$this->updateStructs($get["pars"]);
				break;
			case 'delStruct':
				$this->deleteTypes($get['id'],$this->tables["strukture"],"kom_strukt_id");
				break;
			case 'search':
				$type = getFromInput("t");
				$keyword = trim(readValFromInput("k"));
				$list = isset($_GET["l"])?$_GET["l"]:false;
				if($type == "all"){
					$this->assign("checked_ime"," checked ");
				}else{
					$this->assign("checked_$type"," checked ");
				}
					$this->assign("search_keyword",$keyword);
				$sform = $this->parseTemplate("komitenti/search_form.tpl");
				$this->assign("search_form",$sform);
				$addfuncs = getFromInput("addfuncs");
				//die($type."<br />".$keyword);
				switch($type){
					case "viewStatus":
						$this->searchKomitentViewStatus();
						break;
					case "keyword":
						$this->searchKomitentKeyword($keyword);
						break;
					case "ime":
						$this->searchKomitent(array("komitent_name","komitent_name1"),$keyword,$list,$addfuncs);
						break;
					case "sifra":
						$this->searchKomitent("komitent_id",$keyword,$list,$addfuncs);
						break;
					case "pib":
						$this->searchKomitent(array("komitent_pib","komitent_matbr"),$keyword,$list);
						break;
					case "kontakt":
						$this->searchKomitentKontakt($keyword);
						break;
					case "adresa":
						$this->searchKomitentAdresa($keyword);
						break;
					case "zr":
						$this->searchKomitentZR($keyword);
						break;
					case "all":
						$this->searchKomitent("all",$keyword,$list);
						break;
					default:
						$sub = getFromInput("submitted");
						foreach ($post as $k=>$v){
							$v = utf8RawUrlDecode($v);
							$post[$k] = utf8RawChrDecode($v);
						}
						$group = $this->db->getOne("SELECT gid FROM users WHERE id=".$this->getUserId());
						if ($group != 1) {
							$this->assign("admin_comment_start","<!--");
							$this->assign("admin_comment_end","-->");
							
							if ($group!= 4) {
								$this->assign("manager_comment_start","<!--");
								$this->assign("manager_comment_end","-->");
							}
							
							if($group!=5){
								$this->assign("telemarketing_comment_start","<!--");
								$this->assign("telemarketing_comment_end","-->");
							}
						}else{
							$this->assign("manager_comment_start","<!--");
							$this->assign("manager_comment_end","-->");
							$this->assign("telemarketing_comment_start","<!--");
							$this->assign("telemarketing_comment_end","-->");
						}
						switch ($sub){
							case "reportTM":
								$this->advanceSearchReportTM();
								break;
							case 1:
								$this->advanceSearch($post);
								break;
							case 2:
								$this->advanceSearchDel($post);
								break;
							case 3:
								$this->advanceSearchAttribute();
								break;
							case 4:
								$this->advanceSearchProfile();
								break;
							case 5:
								$this->advanceSearchBrand();
								break;
							case 6:
								$this->advanceSearchKampanjeUgovori();
								break;
							default:
								$this->showAdvanceSearch();
								break;
						}
						break;
				}
				break;
			case 'displayOne':
				$this->displayOne($_GET['id']);
				break;
			case 'duplicateKomdelData':
				$this->generateNewDelDataHTML($get["d"],$get["i"]);
				break;
			case 'browse':
			default:
				$this->browse($_GET["f"],$_GET["s"],$_GET['all']);
				break;
		}
	}
	
	function wwwData(){
		$mode = getFromInput("mod");
		switch ($mode){
			case "import":
				//$this->importWWWData();
				$req = $_SERVER['REQUEST_URI'];
				$url = "http://cvet.yellow$req";
				echo implode("",file($url));
				break;
			case "save":
				$this->saveWWWData();
				break;
			default:
				$this->showWWWData($_GET["komdel"]);
				break;
		}
		
	}
	function importWWWData(){
		require_once("ugovori.fox.class.php");
		$komid = getFromInput("komid");
		$ugo = new ugovori_fox($komid);
		echo $ugo->importKomitentWWW();
	}
	function saveWWWData(){
		foreach ($_POST as $k=>$v){
			$v = utf8RawUrlDecode($v);
			$$k = utf8RawChrDecode($v);
		}
		$q = "UPDATE komitenti_delatnosti SET ";
	
// PROFIL
		// tip profila
		$q .= "tip_profila=$tip_profila, ";

		// logo start
		if(preg_match('/^\d{1,2}\.\d{1,2}\.\d{2,4}$/',$logo_start)){
			$logo_start = date2int($logo_start);
		}else{
			$logo_start = -1;
		}
		$q .= "dat_pos=$logo_start, ";
		
		// logo end
		if(preg_match('/^\d{1,2}\.\d{1,2}\.\d{2,4}$/',$logo_end)){
			$logo_end = date2int($logo_end);
		}else{
			$logo_end = -1;
		}
		$q .= "dat_istek=$logo_end, ";
		
		// logo
		$q .= "logo='$logo_path', ";
		

// BANER
		// tip banera
		$q .= "baner_tip=$baner_tip, ";
		
		// baner title
		$q .= "baner_title='".addslashes($baner_title)."', ";
		
		// baner
		$q .= "baner_name='".addslashes($baner_name)."', ";
		
		// baner_link
		$q .= "baner_link='".addslashes($baner_link)."',";
		
		// baner start
		if(preg_match('/^\d{1,2}\.\d{1,2}\.\d{2,4}$/',$baner_start)){
			$baner_start = date2int($baner_start);
		}else{
			$baner_start = -1;
		}
		$q .= "baner_start=$baner_start, ";
		
		// baner end
		if(preg_match('/^\d{1,2}\.\d{1,2}\.\d{2,4}$/',$baner_end)){
			$baner_end = date2int($baner_end);
		}else{
			$baner_end = -1;
		}
		$q .= "baner_end=$baner_end, ";
		
// HOSTING
		// hosting
		if(preg_match('/^\d{1,2}\.\d{1,2}\.\d{2,4}$/',$hosting)){
			$hosting = date2int($hosting);
		}else{
			$hosting = -1;
		}
		$q .= "dat_hosting=$hosting, ";
		
		// test adresa
		$q .= "test_adresa='$test_adresa', ";
		
		// konacna adresa
		$q .= "kon_adresa='$kon_adresa' ";
		
		$q .= " WHERE komdel_id=$komdel";
		
		if($this->db->alterTable($q)){
			echo "Podaci za internet su sačuvani.";
			$change = new log_change();
			$change->user = $_COOKIE["ypu"];
			$change->ip = $_SERVER['REMOTE_ADDR'];
			$change->time = time();
			$change->table = "komitenti_delatnosti";
			$change->attr = "komdel_id";
			$change->value = $komdel;
			$change->state = 2;
			$change->write();
		}else{
			echo mysql_error();
		}
		
	}
	function showWWWData($id){
		
		$q = "SELECT "
				."tip_profila, logo, dat_pos, dat_istek, baner_tip, baner_name, baner_title, baner_link, baner_start, baner_end, "
				."dat_hosting, test_adresa, kon_adresa, komdel_kom_id, komdel_del_id "
			."FROM komitenti_delatnosti WHERE komdel_id=$id LIMIT 1";
		$res = $this->db->getRow($q,true);
		if($res){
			$polja = $this->get_ProfiliTipovi($res["tip_profila"]);
				$this->assign("tip_profila_id",$polja["id"]);
				$this->assign("tip_profila_name",$polja["name"]);
				$this->assign("tip_profila_desc",$polja["desc"]);
				$this->assign("tip_profila_selected",$polja["selected"]);
			
			$this->assign("komitent_id",$res["komdel_kom_id"]);
			$this->assign("del_id",$res["komdel_del_id"]);
				
			$this->assign("logo",$res["logo"]);
			if($res["dat_pos"]>0)
			$this->assign("logo_start",date($this->getFromConfig("short_date"),$res["dat_pos"]));
			if($res["dat_istek"]>0)
			$this->assign("logo_end",date($this->getFromConfig("short_date"),$res["dat_istek"]));
			
			$polja = $this->get_BaneriTipovi($res["baner_tip"]);
				$this->assign("baner_tip_id",$polja["id"]);
				$this->assign("baner_tip_name",$polja["name"]);
				$this->assign("baner_tip_desc",$polja["desc"]);
				$this->assign("baner_tip_selected",$polja["selected"]);
			$this->assign("baner_name",$res["baner_name"]);
			$this->assign("baner_title",$res["baner_title"]);
			$this->assign("baner_link",$res["baner_link"]);
			if($res["baner_start"]>0)
			$this->assign("baner_start",date($this->getFromConfig("short_date"),$res["baner_start"]));
			if($res["baner_end"]>0)
			$this->assign("baner_end",date($this->getFromConfig("short_date"),$res["baner_end"]));
			
			if($res["dat_hosting"]>0)
			$this->assign("hosting",date($this->getFromConfig("short_date"),$res["dat_hosting"]));
			$this->assign("test_adresa",$res["test_adresa"]);
			$this->assign("kon_adresa",$res["kon_adresa"]);
		}else{
			//echo $q;
			//echo $id;
		}
		$this->assign("firstLabelWidth",65);
		$this->assign("secondLabelWidth",100);
		$this->assign("komdel",$id);
		
		echo $this->parseTemplate("komitenti/www_data.tpl");
	}
	
	function displayNew(){
		
		$ip = $_SERVER['REMOTE_ADDR'];
		
		$kom_max_id = $this->db->getOne("SELECT max(komitent_id) FROM komitenti LIMIT 1");
		$kom_max_id;
		
		$id = $this->db->getRow("SELECT min(id),max(id) FROM komitenti_id_counter");
		
		$ok=true;
		$i = $kom_max_id;
		while($ok){
			$i++;
			$used = $this->db->getOne("SELECT 1 FROM komitenti_id_counter WHERE id=$i");
			if(!$used){
				$ok=false;
				$id = $i;
			}
		}
		//echo $id;
		if($this->db->getOne("SELECT 1 FROM komitenti_id_counter WHERE ip='$ip'")){
			$this->db->alterTable("UPDATE komitenti_id_counter SET id=$id WHERE ip='$ip'");
		}else{
			$this->db->alterTable("INSERT INTO komitenti_id_counter VALUES($id,'$ip')");
		}
		//$id++;
		//$this->db->alterTable("UPDATE komitenti_id_counter SET id=$id LIMIT 1") or die("Greška pri rezervisanju nove šifre komitenta");
		
		$this->assign("komitent_id",$id);
		
		$polja = $this->get_TipoviKomitenata();
			$this->assign("type_id",$polja["id"]);
			$this->assign("type_name",$polja["name"]);
		$polja = $this->get_StruktureKomitenata();
			$this->assign("strukt_id",$polja["id"]);
			$this->assign("strukt_name",$polja["name"]);
		$polja = $this->get_ViewStatus();
			$this->assign("vs_id",$polja["id"]);
			$this->assign("vs",$polja["name"]);
		
		// ADRESA
		$this->assignAdresaObjects();
		
		$polja = $this->get_NaciniPlacanja();
			$this->assign("np_id",$polja["id"]);
			$this->assign("np_name",$polja["name"]);
		$polja = $this->get_Banke();
			$this->assign("banka_id",$polja["id"]);
			$this->assign("banka_name",$polja["name"]);
			$this->assign("select_sve_banke",$this->parseTemplate("sve_banke_select.tpl"));
		$polja = $this->get_Radnici();
			$this->assign("radnik_id",$polja["id"]);
			$this->assign("radnik_name",$polja["name"]);
		/*$polja = $this->get_Kampanje();
			$this->assign("kampanja_id",$polja["id"]);
			$this->assign("kampanja_name",$polja["name"]);
			$this->assign("kampanja_datum",$polja["date"]);*/
		$polja = $this->get_Delatnosti();
			$this->assign("del_id",$polja["id"]);
			$this->assign("del_name",$polja["name"]);
			$this->assign("del_parent",$polja["parent"]);
		$style = array(
			"br" => ' style="clear:both; display:none;"'
		);
		$komitent_adresa = getAdresaHtml("","sve","_komitent",$style,2);
		$this->assign("komitent_adresa",$komitent_adresa);
			
		// template
		$this->assign("dels_data_count","template");
		$this->assign("dels_data_count1",array(1));
		$this->assign("komdel_delid","");
		$this->assign("del_data_tpl",$this->parseTemplate("komitenti/view/del_data_template.tpl"));
		$this->assign("del_template",$this->parseTemplate("komitenti/view/del_template.tpl"));
		
		$this->assign("delatnosti_html",$this->parseTemplate("komitenti/view/one_delatnosti.tpl"));
		
		$this->assign("podaci_left_html",$this->parseTemplate("komitenti/new/new_podaci1.tpl"));
		$this->assign("podaci_right_html",$this->parseTemplate("komitenti/new/new_podaci2.tpl"));
		$this->assign("delatnosti_html",$this->parseTemplate("komitenti/new/new_delatnosti.tpl"));
		echo $this->parseTemplate("komitenti/new/new.tpl");
	}
	function addNew($id){
		if($this->db->alterTable("INSERT INTO komitenti(komitent_id) VALUES($id)")){
			/*if($last = $this->db->getOne("SELECT LAST_INSERT_ID() FROM komitenti")){
				return $last;
			}else{
				die(mysql_error());
			}*/
			return true;
		}else{
			die(mysql_error());
		}
	}
	
	function delKomitent($id){
		
		// test TM, duznici, preporuke
		$tm = $this->db->getOne("SELECT 1 FROM rokovnik WHERE komitent_id=$id AND kontakt!=10 LIMIT 1");
		$du = $this->db->getOne("SELECT 1 FROM duznici WHERE komitent=$id LIMIT 1");
		$pr = $this->db->getOne("SELECT 1 FROM preporuke WHERE kom_id=$id LIMIT 1");
		if ($tm || $du || $pr) {
			if ($tm) {
				echo "Komitent ima pozive u rokovnik/telemarketing.\n";
			}
			if ($du) {
				echo "Komitent ima pozive u rokovnik/dužnici.\n";
			}
			if ($pr) {
				echo "Komitent ima preporuke.\n";
			}
			
			die("\nBrisanje nije izvršeno.");
		}
		
		/*
		TABLES:
		komitenti
		komitenti_delatnosti
		komitenti_np
		komitenti_ziro_racuni
		komitenti_telefoni
		komitenti_rvreme
		komitenti_webs
		komitenti_emails
		komitenti_brands
		komitenti_radnici
		komitenti_kwords
		komitenti_kartice
		profili
		*/
		//echo $id;
		$komdels = $this->db->select2("SELECT komdel_id FROM komitenti_delatnosti WHERE komdel_kom_id=$id");
		$q[] = "DELETE FROM komitenti WHERE komitent_id=$id;";
		$q[] = "DELETE FROM komitenti_delatnosti WHERE komdel_kom_id=$id;";
		$q[] = "DELETE FROM komitenti_np WHERE kom_id=$id;";
		$q[] = "DELETE FROM komitenti_ziro_racuni WHERE ziro_komitent_id=$id;";
		$q[] = "DELETE FROM komitenti_telefoni WHERE kom_id=$id;";
		$q[] = "DELETE FROM komitenti_rvreme WHERE kom_id=$id;";
		$q[] = "DELETE FROM komitenti_webs WHERE kom_id=$id;";
		$q[] = "DELETE FROM komitenti_emails WHERE kom_id=$id;";
		$q[] = "DELETE FROM komitenti_brands WHERE kom_id=$id;";
		$q[] = "DELETE FROM komitenti_radnici WHERE komrad_komitent_id=$id;";
		$q[] = "DELETE FROM komitenti_kwords WHERE kom_id=$id;";
		$q[] = "DELETE FROM profili WHERE profil_kom_id=$id;";
		if($komdels[0]){
			foreach ($komdels as $komdel){
				$q[] = "DELETE FROM komitenti_kartice WHERE komdel_id=".$komdel["komdel_id"];
				
			}
		}
		//print_r($q);die();
		$msg = "Brisanje izvršeno.";
		$error = false;
		foreach ($q as $query){
			if(!$this->db->alterTable($query)){
				$error = true;
				$msg = mysql_error();
				break;
			}
		}
		
		if(!$error){
			$change = new log_change();
			$change->user = $_COOKIE["ypu"];
			$change->ip = $_SERVER['REMOTE_ADDR'];
			$change->time = time();
			$change->table = "komitenti";
			$change->attr = "komitent_id";
			$change->value = $id;
			$change->state = 3;
			$change->write();
		}
		
		echo $msg;
	}
	
	function save($data){
		
		$data = str_replace('\"','"',$data);
		$komitent = new komitentObject();
		$komitent->fillDataURI($data);
		
		$imaid = intval($this->db->getOne("SELECT 1 from komitenti WHERE komitent_id=$komitent->id LIMIT 1"));
		
		// DA LI POSTOJI KOMITENT SA ISTIM PIB-OM?
		if ($imaid || (strlen($komitent->pib)>0 && !$imaid)) {
			$imapib = intval($this->db->getOne("SELECT 1 FROM komitenti WHERE komitent_pib=$komitent->pib AND komitent_id!=$komitent->id LIMIT 1"));
			if ($imapib>0) {
				die("1{!}Komitent već postoji. (PIB: $komitent->pib)");
			}
		}
		
		// DA LI POSTOJI KOMITENT SA ISTIM MATIČNIM BROJEM?
		if ($imaid || (strlen($komitent->matbr)>0 && !$imaid)) {
			$imamatbr = intval($this->db->getOne("SELECT 1 FROM komitenti WHERE komitent_matbr=$komitent->matbr AND komitent_id!=$komitent->id LIMIT 1"));
			if ($imamatbr>0) {
				die("1{!}Komitent već postoji. (MAT.BR: $komitent->matbr)");
			}
		}
		
		// DA LI JE NOVI KOMITENT?
		if (!$imaid) {
			if(!$this->addNew($komitent->id)){
				die("1{!}".mysql_error());
			}
		}
		
		$tmp = explode("{!}",$data);
		$tmp = $tmp[1];
		$tmp = explode("{=}",$tmp);
		$id = trim($tmp[1]);
		/*echo '<p><input type="button" onclick="LoadRSDoc(\'komitenti.php?a=displayOne&id='.$id.'\',\'setContent\')" value="komitent" /></p><br clear="all" /><pre>';
		print_r($komitent);
		echo "</pre>";die();*/
		/*print_r($komitent);
		die();*/
		
		$q_delete = array();
		$q_update = array();
		$q_insert = array();
		
	// 	PREPARE DATA FOR DB
		if (preg_match('/^\d+\.\d+\.\d+$/',$komitent->dat_osn)) {
			$tmp = explode(".",$komitent->dat_osn);
			$komitent_dat_osn = makeUnixTime(0,0,0,$tmp[1],$tmp[0],$tmp[2]);
		}else{
			$komitent_dat_osn=0;
		}
	
	// GENERATE SQL DATA
	
		//komitenti
			$q = "UPDATE komitenti SET "
				. "komitent_name='".addslashes($komitent->name)."', "
				. "komitent_name1='".addslashes($komitent->name1)."', "
				. "komitent_pib='".$komitent->pib."', "
				. "komitent_matbr='".$komitent->matbr."', "
				. "komitent_tip_id='".$komitent->tip."', "
				. "komitent_str_id='".$komitent->struktura."', "
				. "komitent_dat_osn='".$komitent_dat_osn."', "
				. "komitent_view_status='".$komitent->view_status."', "
				. "komitent_vlasnik_name='".$komitent->vlasnik_name."', "
				. "komitent_vlasnik_jmbg='".$komitent->vlasnik_jmbg."', "
				. "komitent_direktor='".$komitent->direktor."', "
				. "komitent_direktor_tel='".$komitent->direktor_tel."', "
				. "komitent_predst='".$komitent->predstavnik."', "
				. "komitent_predst_tel='".$komitent->predstavnik_tel."', "
				. "komitent_adresa='".$komitent->adresa."', "
				. "komitent_napomena='".addslashes($komitent->napomena)."', "
				. "komitent_toll='".$komitent->toll."', "
				. "komitent_poreklo='".$komitent->poreklo."' "
				. "WHERE komitent_id=".$komitent->id;
			$q_update[] = $q;
			
		//komitenti_np
			$q_delete[] = "DELETE FROM komitenti_np WHERE kom_id=".$komitent->id;
			$q = "INSERT INTO komitenti_np VALUES";
			if($komitent->np[0]){
				foreach ($komitent->np as $np){
					$q .= "(".$komitent->id.",$np), ";
				}
				$q = substr($q,0,strlen($q)-2);
				$q_insert[] = $q;
			}
			
		// komitenti_ziro_racuni
			$q_delete[] = "DELETE FROM komitenti_ziro_racuni WHERE ziro_komitent_id=".$komitent->id;
			$q = "INSERT INTO komitenti_ziro_racuni(ziro_komitent_id,ziro_value,ziro_banka_id) VALUES";
			foreach ($komitent->zr as $zr){
				$q .= "(".$komitent->id.",'".$zr["zr"]."',".$zr["banka"]."), ";
			}
			$q = substr($q,0,strlen($q)-2);
			$q_insert[] = $q;
		
		//komitenti_telefoni, komitenti_faksovi
			$q_delete[] = "DELETE FROM komitenti_telefoni WHERE kom_id=".$komitent->id;
			$q = "INSERT INTO komitenti_telefoni VALUES";
			if($komitent->tel[0]){
				foreach ($komitent->tel as $k_tel=>$tel){
					if (strlen(trim($tel))) {
						$q .= "(".$komitent->id.",0,".$komitent->adresa.",'$tel',0,'$k_tel'), ";
					}					
				}
				$q = substr($q,0,strlen($q)-2);
			}
			if($komitent->fax[0]){
				if($komitent->tel[0])
					$q .= ", ";
				foreach ($komitent->fax as $k_fax=>$fax){
					if (strlen(trim($fax))) {
						$q .= "(".$komitent->id.",0,".$komitent->adresa.",'$fax',1,'$k_fax'), ";
					}
				}
				$q = substr($q,0,strlen($q)-2);
			}
			if($komitent->tel[0] || $komitent->fax[0])
			$q_insert[] = $q;
			
		//komitenti_radno_vreme
			$q_delete[] = "DELETE FROM komitenti_rvreme WHERE komdel_id=0 AND kom_id=".$komitent->id;
			if($komitent->rv["rd"] || $komitent->rv["sub"] || $komitent->rv["ned"]){
				$q_insert[] = "INSERT INTO komitenti_rvreme VALUES("
							 ."0,".$komitent->id.",'".$komitent->rv["rd"]."','".$komitent->rv["sub"]."','".$komitent->rv["ned"]."','')";
			}
			
		//komitenti_web
			$q_delete[] = "DELETE FROM komitenti_webs WHERE del_id=0 AND kom_id=".$komitent->id;
			if($komitent->web[0]){
				$q = "INSERT INTO komitenti_webs VALUES";
				foreach ($komitent->web as $web){
					$q .= "(".$komitent->id.",0,'$web'), ";
				}
				$q = substr($q,0,strlen($q)-2);
				$q_insert[] = $q;
			}
		//komitenti_email
			$q_delete[] = "DELETE FROM komitenti_emails WHERE del_id=0 AND kom_id=".$komitent->id;
			if($komitent->email[0]){
				$q = "INSERT INTO komitenti_emails VALUES";
				foreach ($komitent->email as $mail){
					$q .= "(".$komitent->id.",0,'$mail'), ";
				}
				$q = substr($q,0,strlen($q)-2);
				$q_insert[] = $q;
			}
		
		//komitenti_brands
			$q_delete[] = "DELETE FROM komitenti_brands WHERE kom_id=".$komitent->id;
			if(count($komitent->brand)>0){
				/*$sql = "SELECT brand_id, brand_name FROM brands WHERE ";
				foreach ($komitent->brand as $brk=>$brand){
					$brand = trim($brand);
					$komitent->brand[$brk] = $brand;
					$sql .= "brand_name='".addslashes($brand)."' OR ";
				}
				$sql = substr($sql,0,strlen($sql)-4);
				$res_brands = $this->db->select2($sql);
				$tbl_brands = array();
				if($res_brands !== false){
					foreach ($res_brands as $b){
						$tbl_brands[$b["brand_id"]] = strtolower($b["brand_name"]);
					}
				}
				$q = "INSERT INTO komitenti_brands VALUES";
				foreach ($komitent->brand as $kom_brand){
					$s = array_search(strtolower($kom_brand),$tbl_brands);
					if($s !== false){
						$q .= "(".$komitent->id.",0,$s), ";
					}else{
						$forinsert[] = $kom_brand;
					}
				}
				if(count($forinsert)){
					foreach ($forinsert as $nb){
						$sql = "INSERT INTO brands(brand_name) VALUES('".addslashes($nb)."')";
						$this->db->alterTable($sql);
						
						$ins_id = $this->db->getOne("SELECT brand_id FROM brands WHERE brand_name='".addslashes($nb)."'");
						$q .= "(".$komitent->id.",0,$ins_id), ";
					}
				}
				$q = substr($q,0,strlen($q)-2);*/
				foreach ($komitent->brand as $brandid){
					$brandid = intval($brandid);
					if($brandid>0){
						$q = "INSERT INTO komitenti_brands(kom_id,del_id,brand_id) VALUES($komitent->id,0,$brandid)";
						$q_insert[] = $q;
					}
				}
			}
		
		//komitenti_radnici
			$q_update[] = "UPDATE komitenti_radnici SET komrad_zasluga=0 WHERE komrad_komitent_id=".$komitent->id;
			$ima = $this->db->getOne("SELECT komrad_radnik_id FROM komitenti_radnici WHERE komrad_radnik_id=".$komitent->zasluga." AND komrad_komitent_id=".$komitent->id);
			//$ima = $ima>0?true:false;
			
			if(!$ima){
				$q_insert[] = "INSERT INTO komitenti_radnici(komrad_komitent_id,komrad_radnik_id,komrad_datum) VALUES(".$komitent->id.",".$komitent->zasluga.",".time().")";
			}
			$q_update[] = "UPDATE komitenti_radnici SET komrad_zasluga=1 WHERE komrad_radnik_id=".$komitent->zasluga." AND komrad_komitent_id=".$komitent->id;
			
		//profili srp
			if(strlen($komitent->profil_srp)){
				$ima = $this->db->getOne("SELECT profil_id FROM profili WHERE profil_del_id=0 AND profil_lang='srp' AND profil_kom_id=".$komitent->id);
				if($ima){
					$q_update[] = "UPDATE profili SET profil_text='".addslashes($komitent->profil_srp)."' WHERE profil_id=$ima";
				}else{
					$q_insert[] = "INSERT INTO profili(profil_kom_id,profil_del_id,profil_lang,profil_text) VALUES(".$komitent->id.",0,'srp','".addslashes($komitent->profil_srp)."')";
				}
			}else{
				$q_delete[] = "DELETE FROM profili WHERE profil_del_id=0 AND profil_lang='srp' AND profil_kom_id=".$komitent->id;
			}
		
		//profili eng
			if(strlen($komitent->profil_eng)){
				$ima = $this->db->getOne("SELECT profil_id FROM profili WHERE profil_del_id=0 AND profil_lang='eng' AND profil_kom_id=".$komitent->id);
				if($ima){
					$q_update[] = "UPDATE profili SET profil_text='".addslashes($komitent->profil_eng)."' WHERE profil_id=$ima";
				}elseif (strlen($komitent->profil_eng)){
					$q_insert[] = "INSERT INTO profili(profil_kom_id,profil_del_id,profil_lang,profil_text) VALUES(".$komitent->id.",0,'eng','".addslashes($komitent->profil_eng)."')";
				}
			}else{
				$q_delete[] = "DELETE FROM profili WHERE profil_del_id=0 AND profil_lang='eng' AND profil_kom_id=".$komitent->id;
			}
		
		// DELATNOSTI
		$q_delete[] = "DELETE FROM profili WHERE profil_kom_id=".$komitent->id." AND profil_del_id>0";
		$delatnosti = array();
			if(count($komitent->delatnosti)){
				foreach ($komitent->delatnosti as $komdel){
					//file_put_contents("tmpVOJA",var_export($komitent->delatnosti,true));
				  //profili srp
					if(strlen($komdel->profil_srp)){
						$q_insert[] = "INSERT INTO profili(profil_kom_id,profil_del_id,profil_lang,profil_text) VALUES(".$komitent->id.",".$komdel->id.",'srp','".addslashes($komdel->profil_srp)."')";
					}
				  
				  //profili eng
					if(strlen($komdel->profil_eng)){
						$q_insert[] = "INSERT INTO profili(profil_kom_id,profil_del_id,profil_lang,profil_text) VALUES(".$komitent->id.",".$komdel->id.",'eng','".addslashes($komdel->profil_eng)."')";
					}
				  
				  //komitenti_emails
				  	$q_delete[] = "DELETE FROM komitenti_emails WHERE del_id=".$komdel->id." AND kom_id=".$komitent->id;
					if($komdel->email[0]){
						$q = "INSERT INTO komitenti_emails VALUES";
						foreach ($komdel->email as $mail){
							$q .= "(".$komitent->id.",".$komdel->id.",'$mail'), ";
						}
						$q = substr($q,0,strlen($q)-2);
						$q_insert[] = $q;
					}
				  
				  //komitenti_webs
				  	$q_delete[] = "DELETE FROM komitenti_webs WHERE del_id=".$komdel->id." AND kom_id=".$komitent->id;
					if($komdel->web[0]){
						$q = "INSERT INTO komitenti_webs VALUES";
						foreach ($komdel->web as $web){
							$q .= "(".$komitent->id.",".$komdel->id.",'$web'), ";
						}
						$q = substr($q,0,strlen($q)-2);
						$q_insert[] = $q;
					}
					
				  
				  $q_delete[] = "DELETE FROM komitenti_kwords WHERE del_id=".$komdel->id." AND kom_id=".$komitent->id;
				  //komitenti_kwords srp
					if($komdel->kword_srb[0]){
						$sql = "SELECT kword_id, kword FROM kljucne_reci WHERE kword_lang='srb' AND (";
						foreach ($komdel->kword_srb as $kw){
							$sql .= "kword='$kw' OR ";
						}
						$sql = substr($sql,0,strlen($sql)-4).")";
						$res_kwords_srb = $this->db->select2($sql);
						$tbl_kw_srb = array();
						if($res_kwords_srb[0]){
							foreach ($res_kwords_srb as $kws){
								$tbl_kw_srb[$kws["kword_id"]] = strtolower($kws["kword"]);
							}
						}
						$q = "INSERT INTO komitenti_kwords VALUES";
						$forinsert = array();
						foreach ($komdel->kword_srb as $kword){
							$s = array_search(strtolower($kword),$tbl_kw_srb);
							if($s !== false){
								$q .= "(".$komitent->id.",".$komdel->id.",$s), ";
							}else{
								$forinsert[] = $kword;
							}
						}
						if(count($forinsert)){
							foreach ($forinsert as $nkw){
								$sql = "INSERT INTO kljucne_reci(kword,kword_lang) VALUES('$nkw','srb')";
								$this->db->alterTable($sql);
								
								$ins_id = $this->db->getOne("SELECT kword_id FROM kljucne_reci WHERE kword_lang='srb' AND kword='$nkw'");
								$q .= "(".$komitent->id.",".$komdel->id.",$ins_id), ";
							}
						}
						$q = substr($q,0,strlen($q)-2);
						$q_insert[] = $q;
					}
				  
				//komitenti_kwords eng
					if($komdel->kword_eng[0]){
						$sql = "SELECT kword_id, kword FROM kljucne_reci WHERE kword_lang='eng' AND (";
						foreach ($komdel->kword_eng as $kw){
							$sql .= "kword='$kw' OR ";
						}
						$sql = substr($sql,0,strlen($sql)-4).")";
						$res_kwords_eng = $this->db->select2($sql);
						$tbl_kw_eng = array();
						if($res_kwords_eng[0]){
							foreach ($res_kwords_eng as $kws){
								$tbl_kw_eng[$kws["kword_id"]] = strtolower($kws["kword"]);
							}
						}
						$q = "INSERT INTO komitenti_kwords VALUES";
						$forinsert = array();
						foreach ($komdel->kword_eng as $kword){
							$s = array_search(strtolower($kword),$tbl_kw_eng);
							if($s !== false){
								$q .= "(".$komitent->id.",".$komdel->id.",$s), ";
							}else{
								$forinsert[] = $kword;
							}
						}
						if(count($forinsert)){
							foreach ($forinsert as $nkw){
								$sql = "INSERT INTO kljucne_reci(kword,kword_lang) VALUES('$nkw','eng')";
								$this->db->alterTable($sql);
								
								$ins_id = $this->db->getOne("SELECT kword_id FROM kljucne_reci WHERE kword_lang='eng' AND kword='$nkw'");
								$q .= "(".$komitent->id.",".$komdel->id.",$ins_id), ";
							}
						}
						$q = substr($q,0,strlen($q)-2);
						$q_insert[] = $q;
					}

				  //komitenti_brands
				  	if(count($komdel->brand)>0){
						/*$sql = "SELECT brand_id, brand_name FROM brands WHERE ";
						foreach ($komdel->brand as $brk=>$brand){
							$brand = trim($brand);
							$komdel->brand[$brk] = $brand;
							$sql .= "brand_name='".addslashes($brand)."' OR ";
						}
						$sql = substr($sql,0,strlen($sql)-4);
						$res_brands = $this->db->select2($sql);
						$tbl_brands = array();
						if($res_brands[0]){
							foreach ($res_brands as $b){
								$tbl_brands[$b["brand_id"]] = strtolower($b["brand_name"]);
							}
						}
						$q = "INSERT INTO komitenti_brands VALUES";
						$forinsert = array();
						foreach ($komdel->brand as $kom_brand){
							$s = array_search(strtolower($kom_brand),$tbl_brands);
							if($s !== false){
								$q .= "(".$komitent->id.",".$komdel->id.",$s), ";
							}else{
								$forinsert[] = $kom_brand;
							}
						}
						if(count($forinsert)){
							foreach ($forinsert as $nb){
								$sql = "INSERT INTO brands(brand_name) VALUES('".addslashes($nb)."')";
								$this->db->alterTable($sql);
								
								$ins_id = $this->db->getOne("SELECT brand_id FROM brands WHERE brand_name='".addslashes($nb)."'");
								$q .= "(".$komitent->id.",".$komdel->id.",$ins_id), ";
							}
						}
						$q = substr($q,0,strlen($q)-2);*/
						foreach ($komdel->brand as $brandid){
							$brandid = intval($brandid);
							if ($brandid>0) {
								$q = "INSERT INTO komitenti_brands(kom_id,del_id,brand_id) VALUES($komitent->id,$komdel->id,$brandid)";
								$q_insert[] = $q;
							}
						}
					}
				
				  // DELATNOST DATA
				  	foreach ($komdel->data as $komdel_data){
				  		$del = $komdel->id."=".$komdel_data->adresa;
				  		if(array_search($del,$delatnosti) === false){
				  			$delatnosti[] = $del;
				  		}
				  	  //komitenti_delatnosti
				  	  	if(!strlen(trim($komdel_data->komdel))){
				  	  		$q = "INSERT INTO komitenti_delatnosti(komdel_kom_id,komdel_del_id,glavna,komdel_adresa_id) "
				  				."VALUES(".$komitent->id.",".$komdel->id.",".$komdel->glavna.",".$komdel_data->adresa.")";
				  			$this->db->alterTable($q);
				  			$q = "SELECT komdel_id FROM komitenti_delatnosti "
				  				."WHERE komdel_kom_id=".$komitent->id." "
				  				."AND komdel_del_id=".$komdel->id." "
				  				."AND komdel_adresa_id=".$komdel_data->adresa;
				  			$new_id = $this->db->getOne($q);
				  			$komdel_data->komdel = $new_id;
				  		}
				  		$komdels[] = $komdel_data->komdel;
				  		$q = "UPDATE komitenti_delatnosti SET "
			  				."komdel_adresa_id=".$komdel_data->adresa.", "
			  				."glavna=".$komdel->glavna." "
			  				."WHERE komdel_id=".$komdel_data->komdel;
			  			$q_update[] = $q;
			  		  
			  		  //komitenti_telefoni
			  		  	$q_delete[] = "DELETE FROM komitenti_telefoni WHERE kom_id=".$komitent->id." AND del_id=".$komdel->id." AND adresa=".$komdel_data->adresa;
						$q = "INSERT INTO komitenti_telefoni VALUES";
						if($komdel_data->tel[0]){
							foreach ($komdel_data->tel as $k_tel=>$tel){
								$q .= "(".$komitent->id.",".$komdel->id.",".$komdel_data->adresa.",'$tel',0,'$k_tel'), ";
							}
							$q = substr($q,0,strlen($q)-2);
						}
						if($komdel_data->fax[0]){
							if($komdel_data->tel[0])
								$q .= ", ";
							foreach ($komdel_data->fax as $k_fax=>$fax){
								$q .= "(".$komitent->id.",".$komdel->id.",".$komdel_data->adresa.",'$fax',1,'$k_fax'), ";
							}
							$q = substr($q,0,strlen($q)-2);
						}
						if($komdel_data->tel[0] || $komdel_data->fax[0])
						$q_insert[] = $q;
			  		  
					  //komitenti_rvreme
					  	$q_delete[] = "DELETE FROM komitenti_rvreme WHERE komdel_id=".$komdel_data->komdel." AND kom_id=".$komitent->id;
						if($komdel_data->rv["rd"] || $komdel_data->rv["sub"] || $komdel_data->rv["ned"]){
							$q = "INSERT INTO komitenti_rvreme VALUES("
								.$komdel_data->komdel.",".$komitent->id.",'".$komdel_data->rv["rd"]
								."','".$komdel_data->rv["sub"]."','".$komdel_data->rv["ned"]."','')";
							$q_insert[] = $q;
						}
					  
			  		  //komitenti_kartice
			  		  	$tbl_komdel_ids = $this->db->select1("SELECT komdel_id FROM komitenti_delatnosti WHERE komdel_kom_id=".$komitent->id);
			  		  	if($tbl_komdel_ids[0]){
				  		  	$q = "DELETE FROM komitenti_kartice WHERE ";
				  		  	foreach ($tbl_komdel_ids as $kd){
				  		  		$q .= "komdel_id=".$kd[0]." OR ";
				  		  	}
				  		  	$q = substr($q,0,strlen($q)-4);
				  		  	$q_delete[] = $q;
			  		  	}
			  		  	if($komdel_data->card[0]){
			  		  		$q = "INSERT INTO komitenti_kartice VALUES";
			  		  		foreach ($komdel_data->card as $card){
			  		  			$q .= "(".$komdel_data->komdel.",$card), ";
			  		  		}
			  		  		$q = substr($q,0,strlen($q)-2);
			  		  		$q_insert[] = $q;
			  		  	}
				  	}
				}
			}
			$res_del_del = $this->db->select2("SELECT komdel_id FROM komitenti_delatnosti WHERE komdel_kom_id=".$komitent->id);
			foreach ($res_del_del as $v){
				if(array_search($v["komdel_id"],$komdels) === false){
					$q_delete[] = "DELETE FROM komitenti_delatnosti WHERE komdel_id=".$v["komdel_id"];
					//echo $v["komdel_id"]."<br />";
				}
			}
		/*echo "<pre>";
		print_r($q_delete);
		print_r($q_update);
		print_r($q_insert);
		echo "</pre>";
		die();*/
		//$this->writeDebug($q_delete,$q_insert,$q_update);
		$ok = true;
		if(count($q_delete)){
			foreach ($q_delete as $del){
				if(!$this->db->alterTable($del)){
					$ok = false;
					break;
				}
			}
		}
		if(count($q_insert) && $ok){
			foreach ($q_insert as $ins){
				if(!$this->db->alterTable($ins)){
					$ok = false;
					$err_q=$ins;
					break;
				}
			}
		}
		if(count($q_update) && $ok){
			foreach ($q_update as $upd){
				if(!$this->db->alterTable($upd)){
					$ok = false;
					break;
				}
			}
		}
		
		if($ok){
			// log changes
			/*$tables = array(
				'komitenti_np',
				'komitenti_ziro_racuni',
				'komitenti_telefoni',
				'komitenti_rvreme',
				'komitenti_webs',
				'komitenti_emails',
				'komitenti_brands',
				'komitenti_kwords',
				'komitenti_kartice',
				'profili',
				'komitenti',
				'komitenti_radnici',
				'komitenti_delatnosti'
			);*/
			
			$change = new log_change();
			$change->user = $_COOKIE["ypu"];
			$change->ip = $_SERVER['REMOTE_ADDR'];
			$change->time = time();
			$change->table = "komitenti";
			$change->attr = "komitent_id";
			$change->value = $komitent->id;
			
			if($imaid){
				$change->state = 2;
			}else{
				$change->state = 1;
			}
			
			$change->write();
			/*
			//file_put_contents("tmpvoja",var_export($change->user,true));
			if (intval($change->user)==2) {
				$change->addDB();
			}else{
				$hasLog = $change->hasLog($change->user);
				
				if ($hasLog === false) {
					$change->write();
				}else{
					$change->write("$hasLog");
				}
			}*/
			
			echo "0{!}Izmene sačuvane.";
		}else{
			echo "1{!}"."$del$ins$upd\n\n".mysql_error();
		}
	}
	function writeDebug($del,$ins,$upd){
		$del = implode("\r\n",$del);
		$ins = implode("\r\n",$ins);
		$upd = implode("\r\n",$upd);
		
		$fp = @fopen("queryLog.log","w");
		fwrite($fp,"$del\r\n\r\n\r\n$ins\r\n\r\n\r\n$upd");
	}
	
	
	function browse($filter,$step,$all){
		$num_all = $this->db->getOne("SELECT count(komitent_id) FROM komitenti");
		if(!count($this->_configArej)){
			$this->loadConfig();
		}
		$max_list = intval($this->_configArej["max_list"]);
		
		$ss = $step>0?$step:1;
		
		$start = ($ss-1)*$max_list;
		
		$sql = "SELECT * FROM komitenti";
		
		if($filter){ // FILTER po slovu
			$sql .= " WHERE komitent_name LIKE '$filter%'";
			$this->assign("filter_letter",$filter);
			$this->currentFilter($filter);
			$sql .= " ORDER BY komitent_name";
		}else{
			if(isset($step)){
				$this->currentFilter($step);
				$sql .= " ORDER BY komitent_id";
				$sql .= " LIMIT $start,$max_list";
			}else{
				$sql .= " ORDER BY komitent_id";
				if(!$all){
					$sql .= " LIMIT 0,$max_list";
				}else{
					$this->currentFilter("sve");
				}
			}
		}
		//echo $sql;
		$res = $this->db->select2($sql);
		$this->generateLetters();
		if($num_all > $max_list){
			$num_pages = bcdiv($num_all,$max_list,0);
			$rest = $num_all%$max_list;
			if($rest){
				$num_pages++;
			}
			if($num_pages > 10){
				$start_counter = $ss-5;
				if($start_counter<1){
					$start_counter=1;
					$end_counter =11;
				}else{
					$end_counter = $ss+5;
					if($end_counter>$num_pages){
						$end_counter=$num_pages;
						if (($end_counter-$start_counter)<10) {
							$start_counter = $end_counter-10;
						}
					}
				}
			}else{
				$start_counter=1;
				$end_counter=$num_pages;
			}
			for($i=$start_counter; $i<=$end_counter; $i++){
				$numbers[] = $i;
				if($i==1 && !$all){
					$currents[] = "current";
				}else{
					$currents[] = "";
				}
			}
			$this->assign("ukupno_strana",$num_pages);
			$this->assign("current",$currents);
			$this->assign("strana",$numbers);
			$this->assign("divide_pages",'<div class="hr">&nbsp;</div><li><strong>Strana:</strong></li>');
		}
		if($res){
			$c = count($res);
			$this->assign("count",$c);
			foreach($res as $v){
				$sifre[] = $v["komitent_id"];
				$imena[] = $v["komitent_name"];
				
				// adresa
				$adresa_id = $v["komitent_adresa"];
				$adr = $this->adrese->getAll($adresa_id);
				$mesta[] = $adr["lokacija"]["mesto"]["name"];
				$ulice[] = $adr["ulica"];
				$brojevi[] = $adr["broj"];
				
				// telefoni
				if($tels = $this->get_Telefoni($v["komitent_id"],null,null,0)){
					$tels = $tels[0];
					$telefoni[] = $tels["telefon"];
				}else{
					$telefoni[] = "";
				}
			}
			$this->assign("sifra",$sifre);
			$this->assign("ime",$imena);
			$this->assign("mesto",$mesta);
			$this->assign("ulica",$ulice);
			$this->assign("broj",$brojevi);
			$this->assign("telefon",$telefoni);
			
			$tbl = $this->parseTemplate("komitenti/browseTbl.tpl");
			$this->assign("tabela_komitenata",$tbl);
			echo $this->parseTemplate("komitenti/search_form_compact.tpl");
		}else{
			echo $this->parseTemplate("komitenti/search_form_compact.tpl");
			//$this->assign("comm_start","<!--");
			//$this->assign("comm_end","-->");
			$this->noRecords();
		}
		echo $this->parseTemplate("komitenti/browse.tpl");
	}
	function displayOne($id){
		//get all db resorces
		$types = $this->db->select2("SELECT * FROM komitenti_tipovi ORDER BY kom_tip_name");
		
		$foxid = $this->getFoxID($id);
		$this->assign("komitent_fox_id",$foxid);
		//echo "$id -> $foxid";
		
		$kom = new komitentObject($id);
		//print_rarray($kom->delatnosti);
		
		// poslednja izmena
		$lastUser = $this->getLastUser($id);
		if ($lastUser !== false) {
			
			$stateMSG = array(
				1 => "novi",
				2 => "izmena",
				3 => "obrisan"
			);
			
			$tooltip  = '<strong>Poslednja izmena</strong>';
			$tooltip .= '<br />korisnik: '.$lastUser["ime"]." ".$lastUser["prezime"];
			$tooltip .= '<br />vreme: '.date($this->getFromConfig("long_date"),$lastUser["time"]);
			$tooltip .= '<br />akcija: '.$stateMSG[$lastUser["state"]];
			$this->assign("last_user",$tooltip);
		}else{
			$this->assign("lastUserCommentStart","<!--");
			$this->assign("lastUserCommentEnd","-->");
		}
		
		// TELEMARKETING pozivi
		$tmCall = $this->db->getOne("SELECT time FROM rokovnik WHERE komitent_id=$id ORDER BY time DESC LIMIT 1");
		if ($tmCall!==null) {
			$this->assign("TMCallTime",int2date($tmCall,"d.m.Y H:i"));
		}else{
			$this->assign("tmCallCommentStart","<!--");
			$this->assign("tmCallCommentEnd","-->");
		}
		
		// kontakti komercijala
		$q = "SELECT radnik_ime, radnik_prezime, lok_naziv, time_ishod "
			."FROM radnici r, komercijala_kontakti kk, lokacije l "
			."WHERE kk.radnik=r.radnik_id "
			."AND kk.lokacija=l.lid "
			."AND kk.active=1 "
			."AND komitent = $id";
		$komContact = $this->db->select2($q);
		if ($komContact!==false) {
			$kccontent = "";
			foreach ($komContact as $kckey=>$kc){
				$kccontent .= "<strong>".$kc["radnik_ime"]." ".$kc["radnik_prezime"]."</strong>";
				$kccontent .= "<br />".$kc["lok_naziv"];
				if ($kc["time_ishod"]>0) {
					$kccontent .= ", ".int2date($kc["time_ishod"]);
				}
				$kccontent .= "<br />";
			}
			$this->assign("komContact",$kccontent);
		}else{
			$this->assign("komContactStart","<!--");
			$this->assign("komContactEnd","-->");
		}
		
		// firefox bug
		$bug_del = new komitent_delatnost("del0");
		$bug_del_data = new komitent_delatnost_data();
		$bug_del->data[] = $bug_del_data;
		$kom->delatnosti["del0"] = $bug_del;
		
		// top navigation
		$record_first = $this->db->getOne("SELECT komitent_id FROM komitenti ORDER BY komitent_id ASC LIMIT 1");
		$record_prev = $this->db->getOne("SELECT komitent_id FROM komitenti WHERE komitent_id < $id ORDER BY komitent_id DESC LIMIT 1");
		$record_next = $this->db->getOne("SELECT komitent_id FROM komitenti WHERE komitent_id > $id ORDER BY komitent_id ASC LIMIT 1");
		$record_last = $this->db->getOne("SELECT komitent_id FROM komitenti ORDER BY komitent_id DESC LIMIT 1");
		$record_prev = isset($record_prev)?$record_prev:$id;
		$record_next = isset($record_next)?$record_next:$id;
		$this->assign("sifra_first",$record_first);
		$this->assign("sifra_prev",$record_prev);
		$this->assign("sifra_next",$record_next);
		$this->assign("sifra_last",$record_last);
		
		$this->assign("komitent_id",$kom->id);
		$this->assign("komitent_name",trim($kom->name));
		$this->assign("komitent_name1",trim($kom->name1));
		$this->assign("komitent_pib",$kom->pib);
		$this->assign("komitent_matbr",$kom->matbr);
		
		//****************** tip
		$kom_tip = $kom->tip;
		$type_ids = $type_names = array();
		foreach($types as $k=>$v){
			$type_ids[] = $v["kom_tip_id"];
			$type_names[] = $v["kom_tip_name"];
			if($v["kom_tip_id"] == $kom_tip){
				$selected_tips[] = " selected";
			}else{
				$selected_tips[] = "";
			}
		}
		$this->assign("selected_tip",$selected_tips);
		$this->assign("type_id",$type_ids);
		$this->assign("type_name",$type_names);
		
		//****************** struktura
		$kom_str = $kom->struktura;
		$strukts = $this->db->select2("SELECT * FROM komitenti_strukture ORDER BY kom_strukt_name");
		$str_ids = $str_names = array();
		foreach($strukts as $k=>$v){
			$str_ids[] = $v["kom_strukt_id"];
			$str_names[] = $v["kom_strukt_name"];
			if($v["kom_strukt_id"] == $kom_str){
				$selected_strukts[] = " selected";
			}else{
				$selected_strukts[] = "";
			}
		}
		$this->assign("selected_strukt",$selected_strukts);
		$this->assign("strukt_id",$str_ids);
		$this->assign("strukt_name",$str_names);
		
		//****************** datum osnivanja
		if($kom->dat_osn>0){
			$this->assign("komitent_dat_osn",date($this->_configArej["short_date"],$kom->dat_osn));
		}
		
		//****************** view status
		$vs = $kom->view_status;
		$polja = $this->get_ViewStatus();
		$vs_ids = $polja["id"];
		$vs_names = $polja["name"];
		$selected_vs = array("","","");
		$selected_vs[$vs-1] = " selected";
		
		$this->assign("vs_id",$vs_ids);
		$this->assign("vs",$vs_names);
		$this->assign("selected_view_status",$selected_vs);
		
		//****************** vlasnik
		$this->assign("komitent_vlasnik",$kom->vlasnik_name);
		$this->assign("komitent_vlasnik_jmbg",$kom->vlasnik_jmbg);
		
		//****************** direktor
		$this->assign("komitent_direktor",$kom->direktor);
		$this->assign("komitent_direktor_tel",$kom->direktor_tel);
		
		//****************** predstavnik
		$this->assign("komitent_predstavnik",$kom->predstavnik);
		$this->assign("komitent_predstavnik_tel",$kom->predstavnik_tel);
		
		//****************** adresa
		$adr = $kom->adresa;
		$adrese = $this->adrese->getAll($adr);
		$ulica = $adrese["ulica"];
		$ulica_id = $adrese["ulica_id"];
		$broj = $adrese["broj"];
		$this->assign("komitent_adresa_id",$kom->adresa);
		
		//****************** ulica i broj
		$this->assign("komitent_ulica",$ulica);
		$this->assign("komitent_ulica_id",$ulica_id);
		$this->assign("komitent_ul_br",$broj);
		
		//****************** lokacija
		$lokacije = $adrese["lokacija"];
		//echo "<pre>"; print_r($adrese); echo "</pre>";
		//****************** regioni
		$polja_reg = $this->get_Regioni();
			foreach ($polja_reg["polje_id"] as $k=>$regid){
				if($regid == $adrese["region"]["id"]){
					$selected_region[] = " selected";
				}else{
					$selected_region[] = "";
				}
			}
			$this->assign("region_id",$polja_reg["polje_id"]);
			$this->assign("region_name",$polja_reg["polje_ime"]);
			$this->assign("selected_region",$selected_region);
		//****************** opstine
		$polja_ops = $this->get_Opstine();
			foreach ($polja_ops["polje_id"] as $k=>$opsid){
				if($opsid == $adrese["opstina"]["id"]){
					$selected_opstina[] = " selected";
				}else{
					$selected_opstina[] = "";
				}
			}
			$this->assign("opstina_id",$polja_ops["polje_id"]);
			$this->assign("opstina_name",$polja_ops["polje_ime"]);
			$this->assign("opstina_parent",$polja_ops["polje_parent"]);
			$this->assign("kom_selected_opstina",$selected_opstina);
		//****************** mesta
		$polja_mes = $this->get_Mesta();
			foreach ($polja_mes["polje_id"] as $k=>$mid){
				if($mid == $adrese["lokacija"]["mesto"]["id"]){
					$selected_mesto[] = " selected";
				}else{
					$selected_mesto[] = "";
				}
			}
			$this->assign("mesto_id",$polja_mes["polje_id"]);
			$this->assign("mesto_name",$polja_mes["polje_ime"]);
			$this->assign("mesto_parent",$polja_mes["polje_parent"]);
			$this->assign("mesto_ptt",$polja_mes["polje_ptt"]);
			$this->assign("kom_selected_mesto",$selected_mesto);
		//****************** lok.opstine
		$polja_lops = $this->get_LokOpstine();
			foreach ($polja_lops["polje_id"] as $k=>$lopsid){
				if($lopsid == $adrese["lokacija"]["opstina"]["id"]){
					$selected_lok_opstina[] = " selected";
				}else{
					$selected_lok_opstina[] = "";
				}
			}
			$this->assign("lok_opstina_id",$polja_lops["polje_id"]);
			$this->assign("lok_opstina_name",$polja_lops["polje_ime"]);
			$this->assign("lok_opstina_parent",$polja_lops["polje_parent"]);
			$this->assign("lok_opstina_ptt",$polja_lops["polje_ptt"]);
			$this->assign("kom_selected_lok_opstina",$selected_lok_opstina);	
		//****************** naselja
		$polja_nas = $this->get_Naselja();
			foreach ($polja_nas["polje_id"] as $k=>$nasid){
				if($nasid == $adrese["lokacija"]["naselje"]["id"]){
					$selected_naselje[] = " selected";
				}else{
					$selected_naselje[] = "";
				}
			}
			$this->assign("naselje_id",$polja_nas["polje_id"]);
			$this->assign("naselje_name",$polja_nas["polje_ime"]);
			$this->assign("naselje_parent",$polja_nas["polje_parent"]);
			$this->assign("naselje_ptt",$polja_nas["polje_ptt"]);
			$this->assign("kom_selected_naselje",$selected_naselje);
		
		//nacini placanja
		if($kom_nps = $this->db->select1("SELECT np_id FROM komitenti_np WHERE kom_id=$id")){
			foreach ($kom_nps as $kom_np){
				$tmp[] = $kom_np[0];
			}
			$kom_nps = $tmp;
		}else{
			$kom_nps = array();
		}
		$nps = $this->db->select2("SELECT * FROM komitent_nacini_placanja ORDER BY komitent_np_id");
		foreach ($nps as $np){
			$np_ids[] = $np["komitent_np_id"];
			$np_names[] = $np["komitent_np_name"];
			if(in_array($np["komitent_np_id"],$kom_nps) !== FALSE){
				$selected_np[] = " checked";
			}else{
				$selected_np[] = "";
			}
		}
		$this->assign("np_id",$np_ids);
		$this->assign("np_name",$np_names);
		$this->assign("selected_np",$selected_np);
		//napomena
		$this->assign("komitent_napomena",$kom->napomena);
		//banke, ziro racuni
		$banke = $this->db->select2("SELECT * FROM banke ORDER BY banka_name");
		$banke_ids = $banke_names = $selected_banka = array();
		foreach($banke as $k=>$banka){
			$banke_ids[] = $banka["banka_id"];
			$banke_names[] = $banka["banka_name"];
		}
		if(count($kom->zr)){
			foreach ($kom->zr as $k=>$zr){
				$this->assign("select_banka_name","komitent_banka_$k");
				$selected_banka = array_fill(0,count($banke_ids),"");
				if(($s = array_search($zr["banka_id"],$banke_ids)) !== false){
					$selected_banka[$s] = " selected";
				}
				$this->assign("banka_id",$banke_ids);
				$this->assign("banka_name",$banke_names);
				$this->assign("selected_banka",$selected_banka);
				$html = $this->parseTemplate("sve_banke_select.tpl");
				$sve_banke[] = $html;
				$zr_num[] = $k+1;
				$banka_zr[] = $zr["ziro"];
				if(!$k){
					$comment_remove_start[] = "<!--";
					$comment_remove_end[] = "-->";
				}else{
					$comment_remove_start[] = "";
					$comment_remove_end[] = "";
				}
			}
			$this->assign("comment_start_remove_banka",$comment_remove_start);
			$this->assign("comment_end_remove_banka",$comment_remove_end);
			$this->assign("zr_num",$zr_num);
			$this->assign("select_sve_banke",$sve_banke);
			$this->assign("banka_zr",$banka_zr);
		}else{
			$this->assign("comment_start_remove_banka","<!--");
			$this->assign("comment_end_remove_banka","-->");
			$this->assign("zr_num",array(1));
			$this->assign("banka_id",$banke_ids);
			$this->assign("banka_name",$banke_names);
			$sve_banke_html = $this->parseTemplate("sve_banke_select.tpl");
			$this->assign("select_sve_banke",array($sve_banke_html));
			$this->assign("banka_zr",array(""));
		}
		//telefoni - faksovi
		//$q = "SELECT * FROM komitenti_telefoni WHERE kom_id=$id";
		$tels = $this->get_Telefoni($id);
		if($tels){
			foreach ($tels as $tel){
				if(!$tel["del_id"]){
					if($tel["fax"]){
						$faxs[] = $tel["telefon"];
					}else{
						$telefoni[] = $tel["telefon"];
					}
				}
			}
			$this->assign("komitent_telefoni",@implode("\n",$telefoni));
			$this->assign("komitent_faxovi",@implode("\n",$faxs));
		}
		//emails
		$mails = $this->db->select2("SELECT * FROM komitenti_emails WHERE kom_id=$id");
		if($mails){
			foreach ($mails as $mail){
				if(!$mail["del_id"]){
					$kom_mail[] = $mail["email"];
				}
			}
			$this->assign("komitent_mails",@implode("\n",$kom_mail));
		}
		//webs
		$webs = $this->db->select2("SELECT * FROM komitenti_webs WHERE kom_id=$id");
		if($webs){
			foreach ($webs as $web){
				if(!$web["del_id"]){
					$kom_web[] = $web["web"];
				}
			}
			if(count($kom_web)){
				$kom_web = implode("\n",$kom_web);
				$this->assign("komitent_webs",$kom_web);
			}
		}
		//TOLL
		if($kom->toll){
			$this->assign("komitent_toll",$kom->toll);
		}
		//brands
		if($kom->brand){
			foreach ($kom->brand as $brand_id=>$brand){
				$kom_brand_ids[] = $brand_id;
				$kom_brands[] = $brand;
			}
			$this->assign("kombrand_id",$kom_brand_ids);
			$this->assign("kombrand_name",$kom_brands);
		}
		//radnici
		$radnik_zasluga = $this->db->getRow("SELECT komrad_radnik_id FROM komitenti_radnici WHERE komrad_komitent_id=$id AND komrad_zasluga=1 LIMIT 1");
		$radnik_zasluga = $radnik_zasluga[0];
		$radnici = $this->db->select2("SELECT radnik_id, CONCAT(radnik_ime,' ',radnik_prezime) as ime FROM radnici ORDER BY ime asc");
		foreach ($radnici as $radnik){
			$rad_ids[] = $radnik["radnik_id"];
			$rad_names[]=$radnik["ime"];
			if($radnik["radnik_id"] == $radnik_zasluga){
				$selected_radnik[] = " selected";
			}else{
				$selected_radnik[] = "";
			}
		}
		$this->assign("radnik_id",$rad_ids);
		$this->assign("radnik_name",$rad_names);
		$this->assign("selected_radnik",$selected_radnik);
		//kampanje
		$q = "SELECT kampanje.kampanja_naziv, kampanje.kampanja_id, kampanje.kampanja_start_date, kampanje.kampanja_end_date "
			."FROM kampanje, komitenti_kampanje "
			."WHERE komitenti_kampanje.komitent_id=$id AND "
			."komitenti_kampanje.kampanja_id=kampanje.kampanja_id "
			."ORDER BY kampanje.kampanja_start_date DESC";
		if($kampanje = $this->db->select2($q)){
			foreach ($kampanje as $kampanja){
				$komkam_ids[]=$kampanja["kampanja_id"];
				$komkam_names[] = $kampanja["kampanja_naziv"];
				$start_date = date($this->_configArej["short_date"],$kampanja["kampanja_start_date"]);
				$end_date = date($this->_configArej["short_date"],$kampanja["kampanja_end_date"]);
				$datumi[] = $start_date." - ".$end_date;
			}
			$this->assign("kampanja_id",$komkam_ids);
			$this->assign("kampanja_name",$komkam_names);
			$this->assign("kampanja_datum",$datumi);
		}
		//poreklo
			$this->assign("komitent_poreklo",$kom->poreklo);
		//radno vreme
		if($kom->rv){
			$this->assign("komitent_rv_dan",$kom->rv["rd"]);
			$this->assign("komitent_rv_sub",$kom->rv["sub"]);
			$this->assign("komitent_rv_ned",$kom->rv["ned"]);
		}
		//profili
		if($profili = $this->db->select2("SELECT * FROM profili WHERE profil_kom_id=$id")){
			foreach ($profili as $profil){
				if($profil["profil_del_id"]==0){
					if($profil["profil_lang"]=="srp"){
						$profil_srp=$profil["profil_text"];
					}else{
						$profil_eng=$profil["profil_text"];
					}
				}
			}
			$this->assign("komitent_profil",$profil_srp);
			$this->assign("komitent_profile",$profil_eng);
		}
		
		// kartice
		if($cards = $this->db->select2("SELECT * FROM kartice ORDER BY card_name")){
			foreach ($cards as $card){
				$card_ids[] = $card["card_id"];
				$card_names[] = $card["card_name"];
			}
			$this->assign("card_id",$card_ids);
			$this->assign("card_name",$card_names);
		}
		$q = "SELECT kk.*, k.card_name "
			."FROM komitenti_kartice kk, komitenti_delatnosti kd, kartice k "
			."WHERE kk.komdel_id=kd.komdel_id "
			."AND kk.card_id=k.card_id "
			."AND kd.komdel_kom_id=".$kom->id;
		$komdel_all_cards = $this->db->select2($q);
		
	  /****************************************************/
	 /********************** DELATNOSTI ******************/
	/****************************************************/
		
	// delatnosti na ugovoru
	// zabrani brisanje
	$q = "SELECT DISTINCT id, broj, datum, delatnost "
		."FROM ugovori, ugovori_stavke "
		."WHERE ugovori.id=ugovori_stavke.ugovor_id "
		."AND ugovori.komitent=$kom->id "
		."ORDER BY datum DESC "
		."LIMIT 1";
	$ugodels = $this->db->getRow($q,true);
	if ($ugodels !== null) {
		$ugovor_dels = ";".$ugodels["delatnost"].";";
		$ugovor_dels_dat = datetime2str($ugodels["datum"]);
		$ugovor_dels_broj = $ugodels["broj"];
		
		// stavke
		$q = "SELECT paket, artikl, kolicina "
			."FROM ugovori_stavke "
			."WHERE ugovor_id=".$ugodels["id"];
		$stavke = $this->db->select2($q);
		$ugovor_stavke = "";
		if ($stavke !== false) {
			foreach ($stavke as $k=>$row){
				if ($row["paket"]>0) {
					$ugovor_stavke .= "[n]".($k+1).". ".$this->db->getOne("SELECT paketname FROM artikli_paketi WHERE paketid=".$row["artikl"]." LIMIT 1");
					$paket_content = $this->db->select1("SELECT cena FROM artikli_paketi_artikli WHERE paket=".$row["artikl"]);
					if ($paket_content) {
						foreach ($paket_content as $prow){
							$art = $this->get_CeneArtikl($prow[0]);
							$ugovor_stavke .= "[n][t]".$art["art_name"];
							if ($art["art_tip_id"]>0) {
								$ugovor_stavke .= ", ".$art["art_tip_name"];
							}
							if ($art["art_boja_id"]>0) {
								$ugovor_stavke .= ", ".$art["art_boja_code"];
							}
							if ($art["art_mera"]>0) {
								$ugovor_stavke .= ", ".$art["art_mera"]." ".$art["art_jmere_sval"];
							}
						}
					}
				}else{
					$art = $this->get_CeneArtikl($row["artikl"]);
					$ugovor_stavke .= "[n]".($k+1).". ".$art["art_name"];
					if ($art["art_tip_id"]>0) {
						$ugovor_stavke .= ", ".$art["art_tip_name"];
					}
					if ($art["art_boja_id"]>0) {
						$ugovor_stavke .= ", ".$art["art_boja_code"];
					}
					if ($art["art_mera"]>0) {
						$ugovor_stavke .= ", ".$art["art_mera"]." ".$art["art_jmere_sval"];
					}
				}
			}
		}
		$this->assign("ugovor_dels_stavke",$ugovor_stavke);
		
		// linkovi
		$q = "SELECT DISTINCT links "
			."FROM ugovori_stavke us, ugovori_tok_realizacije utr, knjiga_data kd "
			."WHERE us.stavka_id=utr.stavka "
			."AND utr.tok_id=kd.id_tok "
			."AND us.ugovor_id=".$ugodels["id"]." "
			."AND LENGTH(links)>0";
		$links = $this->db->select2($q);
		if ($links !== false) {
			foreach ($links as $l){
				$ugovor_dels .= substr($l["links"],1);
			}
		}
		$this->assign("ugovor_dels_broj",$ugovor_dels_broj);
		$this->assign("ugovor_dels",$ugovor_dels);
		$this->assign("ugovor_dels_dat",$ugovor_dels_dat);
	}
	
			
		$dels = $this->db->select2("SELECT * FROM delatnosti ORDER BY delatnost_ime");
		foreach($dels as $del){
			$del_ids[]=$del["delatnost_id"];
			$del_names[] = $del["delatnost_ime"];
			$parent = (int) $this->db->getOne("SELECT 1 FROM delatnosti_nasledjivanje WHERE parent=".$del["delatnost_id"]." LIMIT 1");
			$del_parent[] = $parent>0?"parent":"child";
			$del_parent_disable[] = $parent>0?" disabled":"";
		}
		if ($this->getUserId()==2) {
			//print_rarray($del_parent);
		}
		$this->assign("del_id",$del_ids);
		$this->assign("del_name",$del_names);
		$this->assign("del_parent",$del_parent);
		$dels_data = "";
		if($kom->delatnosti){
			$i=0;
			foreach ($kom->delatnosti as $del_count=>$komdel){
				$i++;
				
				$komdel_ids[] = $komdel->id;
				$komdel_names[] = $komdel->name;
				$komdel_items[] = $i;
				if($komdel->glavna){
					$komdel_checked[] = " checked";
				}else{
					$komdel_checked[] = "";
				}
				// profili
				$this->assign("komdel_profil_srp",$komdel->profil_srp);
				$this->assign("komdel_profil_eng",$komdel->profil_eng);
				
				// email i web
				$this->assign("komdel_email",@implode("\n",$komdel->email));
				$this->assign("komdel_web",@implode("\n",$komdel->web));
				
				// brands
				$komdel_brand_ids = $komdel_brand_names = array();
				if($komdel->brand){
					foreach ($komdel->brand as $brandid=>$brandname){
						$komdel_brand_ids[] = $brandid;
						$komdel_brand_names[] = $brandname;
					}
				}
				$this->assign("komdel_brand_id",$komdel_brand_ids);
				$this->assign("komdel_brand_name",$komdel_brand_names);
				/*if($komdel->brand){
					$this->assign("komdel_brands",@implode("\n",$komdel->brand));
				}else{
					$this->assign("komdel_brands","");
				}*/
				
				// kwords
				$this->assign("komdel_keywords_srb",@implode("\n",$komdel->kword_srb));
				$this->assign("komdel_keywords_eng",@implode("\n",$komdel->kword_eng));
				
				// podaci
				$dels_data_html = "\r\n";
				
				foreach ($komdel->data as $del_data_count=>$komdel_data){
					if ($komdel_data->adresa>=0 || ($komdel->id == "del0")) {
						$this->assign("dels_data_komdel",$komdel_data->komdel);
						$this->assign("komdel_adresa_id",$komdel_data->adresa);
						$this->assign("dels_data_count",$del_count);
						$this->assign("dels_data_count1",$del_data_count+1);
						
						// get address object
						$adr_obj = $this->adrese->getAll($komdel_data->adresa);
						
						// reset arrays
						$selected_region = $selected_opstina = $selected_mesto = $selected_lok_opstina = $selected_naselje = array();
						
						// region
						$selected_region = array();
						foreach ($polja_reg["polje_id"] as $k=>$regid){
							if($regid == $adr_obj["region"]["id"]){
								$selected_region[] = " selected";
							}else{
								$selected_region[] = "";
							}
						}
						$this->assign("komdel_selected_region",$selected_region);
						
						// opstina
						$selected_opstina = array();
						foreach ($polja_ops["polje_id"] as $k=>$opsid){
							if($opsid == $adr_obj["opstina"]["id"]){
								$selected_opstina[] = " selected";
							}else{
								$selected_opstina[] = "";
							}
						}
						$this->assign("komdel_selected_opstina",$selected_opstina);
						
						// mesto
						$selected_mesto = array();
						foreach ($polja_mes["polje_id"] as $k=>$mesid){
							if($mesid == $adr_obj["lokacija"]["mesto"]["id"]){
								$selected_mesto[] = " selected";
							}else{
								$selected_mesto[] = "";
							}
						}
						$this->assign("komdel_selected_mesto",$selected_mesto);
						
						// lok_opstina
						$selected_lok_opstina = array();
						foreach ($polja_lops["polje_id"] as $k=>$lopsid){
							if($lopsid == $adr_obj["lokacija"]["opstina"]["id"]){
								$selected_lok_opstina[] = " selected";
							}else{
								$selected_lok_opstina[] = "";
							}
						}
						$this->assign("komdel_selected_lok_opstina",$selected_lok_opstina);
						// naselje
						$selected_naselje = array();
						foreach ($polja_nas["polje_id"] as $k=>$nasid){
							if($nasid == $adr_obj["lokacija"]["naselje"]["id"]){
								$selected_naselje[] = " selected";
							}else{
								$selected_naselje[] = "";
							}
						}
						$this->assign("komdel_selected_naselje",$selected_naselje);
						
						// ulica i broj
						$ulica_id = $adr_obj["ulica_id"];
						$ulica_name = $adr_obj["ulica"];
						$broj = $adr_obj["broj"];
						$this->assign("komdel_ulica_id",$ulica_id);
						$this->assign("komdel_ulica",$ulica_name);
						$this->assign("komdel_broj",$broj);
						
						// telefon
						
						if($komdel_tels = $kom->getItem($komdel->id,$tels,"del_id",array("del_id","adresa","telefon","fax"))){
							if($ktels = $kom->getItem($komdel_data->adresa,$komdel_tels,"adresa",array("del_id","adresa","telefon","fax"))){
								$komdel_telefoni = $komdel_faksevi = array();
								$komdel_telefoni = $komdel_faksevi = array();
								foreach ($ktels as $ktel){
									if(!$ktel["fax"]){
										$komdel_telefoni[] = $ktel["telefon"];
									}else{
										$komdel_faksevi[] = $ktel["telefon"];
									}
								}
								$this->assign("komdel_tel",@implode("\n",$komdel_telefoni));
								$this->assign("komdel_fax",@implode("\n",$komdel_faksevi));
							}else{
								$this->assign("komdel_tel","");
								$this->assign("komdel_fax","");
							}
						}else{
							$this->assign("komdel_tel","");
							$this->assign("komdel_fax","");
						}
						
						// radno vreme
						$this->assign("komdel_rvreme_rdan",$komdel_data->rv["rd"]);
						$this->assign("komdel_rvreme_sub",$komdel_data->rv["sub"]);
						$this->assign("komdel_rvreme_ned",$komdel_data->rv["ned"]);
						
						// platne kartice
						$komdel_cards = $kom->getItem($komdel_data->komdel,$komdel_all_cards,"komdel_id",array("card_id","card_name"));
						$card_li = array();
						if($komdel_cards){
							$komdel_card_ids = $komdel_card_names = array();
							foreach ($komdel_cards as $item){
								$komdel_card_ids[] = $item["card_id"];
								$komdel_card_names[] = $item["card_name"];
								$card_li[] = '<li value="'.$item["card_id"].'" onclick="if(!this.className.length){this.className=\'selected\'}else{this.className=\'\'}" ondblclick="this.parentNode.removeChild(this)" onmousedown="return false;" title="šifra: '.$item["card_id"].'">'.$item["card_name"].'</li>';
							}
							$this->assign("komdel_card_id",$komdel_card_ids);
							$this->assign("komdel_card_name",$komdel_card_names);
							$this->assign("card_li",$card_li);
						}else{
							$this->assign("komdel_card_id","");
							$this->assign("komdel_card_name","");
							$this->assign("card_li","");
						}
						
						// www data holder
						if($komdel_data->www_params){
							$this->assign("komdel_data_www","url(gui/icons/globe_small.gif) no-repeat center center");
							//$this->assign("komdel_data_www"," background:url(gui/icons/globe.gif) no-repeat 99% 5px");
							$this->assign("www_data_state","1");
							$this->assign("www_data_width",20);
						}else{
							$this->assign("komdel_data_www","none");
							$this->assign("www_data_state","0");
							$this->assign("www_data_width","0");
						}
						//debug($komdel_data);
	
						$this->assign("delid",$komdel->id);
						
						// appending html of delatnost-data
						$append = $this->parseTemplate("komitenti/view/del_data_template.tpl");
						$dels_data_html .= $append;
					}
				}
				$this->assign("komdel_delid",$komdel->id);
				$this->assign("dels_data_count1",count($komdel->data));
				$this->assign("del_data_tpl",$dels_data_html);
				
				$dels_data .= $this->parseTemplate("komitenti/view/del_template.tpl")."\r\n";
			}
			//fwrite(fopen("dbg.log","w"),$dels_data);
			$this->assign("komdel_del_id",$komdel_ids);
			$this->assign("komdel_del_name",$komdel_names);
			$this->assign("komdel_item",$komdel_items);
			$this->assign("checked_komdel_delid",$komdel_checked);
		}
		//print_rarray($kom);
		$this->assign("dels_data",$dels_data);
		$this->assign("debug",$dels_data);
		
		
		$level = $this->getUserLevel();
		//print_rarray($level);
		
		$gid = $level["id"];
		$gname = $level["name"];
		
		if($level["rights"]["komitenti"] == 0){					// brisanje 0, izmena 0
			$this->assign("diz",' disabled="disabled"');
			$this->assign("diz_admin",' disabled="disabled"');
			$this->assign("comm_start",'<!--');
			$this->assign("comm_end",'-->');
		}elseif ($level["rights"]["komitenti"]==1){				// brisanje 0, izmena 1
			$this->assign("diz",' ');
			$this->assign("diz_admin",' disabled="disabled"');
			$this->assign("comm_start",'<!--');
			$this->assign("comm_end",'-->');
		}else{													// brisanje 1, izmena 1
			$this->assign("diz",' ');
			$this->assign("diz_admin",' ');
		}
		
		
		$this->assign("disabled",$this->user_level);
		$sform = $this->parseTemplate("komitenti/search_form_compact.tpl");
		//echo $sform;
		$this->assign("search_compact",$sform);
		
		
		$podaci_left = $this->parseTemplate("komitenti/view/one_podaci1.tpl");
		$this->assign("podaci_left_html",$podaci_left);
		//echo $podaci_left;
		
		$podaci_right = $this->parseTemplate("komitenti/view/one_podaci2.tpl");
		$this->assign("podaci_right_html",$podaci_right);
		//echo $podaci_right;
		
		//template display
		$this->assign("dels_data_count","template");
		$this->assign("dels_data_count1",array(1));
		$this->assign("komdel_delid","");
		
		$del_data_template = $this->parseTemplate("komitenti/view/del_data_template.tpl");
		$this->assign("del_data_tpl",$del_data_template);
		//echo $del_template;
		
		$del_template = $this->parseTemplate("komitenti/view/del_template.tpl");
		$this->assign("del_template",$del_template);
		//echo $del_template;
		
		$delatnosti = $this->parseTemplate("komitenti/view/one_delatnosti.tpl");
		$this->assign("delatnosti_html",$delatnosti);
		//echo $delatnosti;
		
		$html = $this->parseTemplate("komitenti/view/one.tpl");
		echo $html;
	}
	
	function displayTypes(){
		$type_names = $this->getKomitent('kom_tip_name',$this->tables["tipovi"],"kom_tip_name");
		$type_ids = $this->getKomitent('kom_tip_id',$this->tables["tipovi"],"kom_tip_name");
		$this->assign("type_name",$type_names);
		$this->assign("type_id",$type_ids);
		$add = $this->parseTemplate("komitenti/new/new_type.tpl");
		$tmp = explode("<!--divide-->",$add);
		$add = $tmp[0];
		$this->assign("add_new_type",$add);
		echo $this->parseTemplate("komitenti/types.tpl");
	}
	function deleteTypes($ids,$table,$field){
		$tmp = explode(",",$ids);
		$sql = "DELETE FROM ".$table." WHERE ";
		foreach($tmp as $k=>$v){
			$sql .= $field.'='.$v;
			if($k < (count($tmp)-1))
				$sql .=" OR ";
		}
		$state = @$this->db->alterTable($sql);
		if(!$state){
			echo "Brisanje neuspelo!";
		}
	}
	function addType($type,$name){
		switch($type){
			case 'type':
				$sql = "INSERT INTO ".$this->tables["tipovi"]."(kom_tip_name) VALUES('".$name."')";
				break;
			case 'struct':
				$sql = "INSERT INTO ".$this->tables["strukture"]."(kom_strukt_name) VALUES('".$name."')";
				break;
		}
		
		if(isset($sql)){
			$state = @$this->db->alterTable($sql);
			if(!$state){
				echo 'Dodavanje nije uspelo!';
			}
		}
	}
	function editType($ids){
		$idejevi = array();
		$names = array();
		$ids = explode(",",$ids);
		foreach($ids as $k=>$v){
			$sql = "SELECT kom_tip_name FROM ".$this->tables["tipovi"]." WHERE kom_tip_id=".$v."";
			$res = $this->db->select1($sql);
			$res = $res[0];
			$names[] = $res[0];
			$idejevi[] = $v;
		}
		$this->assign("kom_type_id",$idejevi);
		$this->assign("kom_type_name",$names);
		$this->assign("action","types");
		echo $this->parseTemplate("komitenti/edit_type.tpl");
	}
	function updateTypes($params){
		$tmp = explode("{!}",$params);
		$status = true;
		foreach($tmp as $k=>$v){
			$t = explode("{!!}",$v,2);
			$id = $t[0];
			$name = $t[1];
			$sql = "UPDATE ".$this->tables["tipovi"]." SET kom_tip_name='".$name."' WHERE kom_tip_id=".$id;
			if($this->db->alterTable($sql)){
				$status = true;
			}else{
				echo "Query nije uspeo.";
				break;
			}
		}
		if($status){
			echo "<img src=\"gui/icons/ok.gif\" alt=\"\" /> Izmene uspšno izvršene.<br /><a href=\"javascript:void(0)\" onclick=\"LoadRSDoc('komitenti.php?a=types','setContent')\"><strong>nazad</strong></a>";
		}
	}
	
	function displayStructs(){
		$struct_names = $this->getKomitent('kom_strukt_name',$this->tables["strukture"],"kom_strukt_name");
		$struct_ids = $this->getKomitent('kom_strukt_id',$this->tables["strukture"],"kom_strukt_name");
		
		$this->assign("struct_name",$struct_names);
		$this->assign("struct_id",$struct_ids);
		$add = $this->parseTemplate("komitenti/new/new_struct.tpl");
		$tmp = explode("<!--divide-->",$add);
		$add = $tmp[0];
		$this->assign("add_new_struct",$add);
		echo $this->parseTemplate("komitenti/structs.tpl");
	}
	function editStruct($ids){
		$idejevi = array();
		$names = array();
		$ids = explode(",",$ids);
		foreach($ids as $k=>$v){
			$sql = "SELECT kom_strukt_name FROM ".$this->tables["strukture"]." WHERE kom_strukt_id=".$v."";
			$res = $this->db->select1($sql);
			$res = $res[0];
			$names[] = $res[0];
			$idejevi[] = $v;
		}
		$this->assign("kom_type_id",$idejevi);
		$this->assign("kom_type_name",$names);
		$this->assign("action","struct");
		echo $this->parseTemplate("komitenti/edit_type.tpl");
	}
	function updateStructs($params){
		$tmp = explode("{!}",$params);
		$status = true;
		foreach($tmp as $k=>$v){
			$t = explode("{!!}",$v,2);
			$id = $t[0];
			$name = $t[1];
			$sql = "UPDATE ".$this->tables["strukture"]." SET kom_strukt_name='".$name."' WHERE kom_strukt_id=".$id;
			if($this->db->alterTable($sql)){
				$status = true;
			}else{
				echo "Query nije uspeo.";
				break;
			}
		}
		if($status){
			echo "<img src=\"gui/icons/ok.gif\" alt=\"\" /> Izmene uspešno izvršene.<br /><a href=\"javascript:void(0)\" onclick=\"LoadRSDoc('komitenti.php?a=struct','setContent')\"><strong>nazad</strong></a>";
		}
	}
	
	function noRecords(){
		$this->assign("error_msg","<p style=\"margin:0px\" class=\"area\">Nema podataka.</p>");
	}
		function getKomitent($field,$table,$order){
		$ret = array();
		$sql = "SELECT ".$field." FROM ".$table;
		if(isset($order)){
			$sql .= " ORDER BY ".$order;
		}
		$res = $this->db->select1($sql);
		foreach($res as $k=>$v){
			$ret[] = $v[0];
		}
		return $ret;
	}
	
	//----------------------------------------------------------------------------
	
	function searchKomitentViewStatus(){
		
		$vs = getFromInput("filter_view_status");
		$page = getFromInput("page");
		$polja = $this->get_ViewStatus($vs);
			$this->assign("vs_id",$polja["id"]);
			$this->assign("vs_name",$polja["name"]);
			$this->assign("vs_selected",$polja["selected"]);
			
		if($vs>0){
			$page = $page>0?$page:1;
			
			$ukupno = $this->db->getOne("SELECT count(komitent_id) FROM komitenti WHERE komitent_view_status=$vs ORDER BY komitent_name");
			if($ukupno>0){
				$this->assign("info","Ukupno: $ukupno");
				if ($ukupno>PAGE_LENGTH) {
					$num_pages = bcdiv($ukupno,PAGE_LENGTH,0);
					if($ukupno%PAGE_LENGTH>0){
						$num_pages++;
					}
					for ($i=1; $i<=$num_pages; $i++){
						$pages[] = $i;
						$pages_vs[] = $vs;
						if ($i==$page) {
							$current_page[] = "current";
						}else{
							$current_page[] = "";
						}
					}
					$this->assign("page",$pages);
					$this->assign("page_vs",$pages_vs);
					$this->assign("current_page",$current_page);
				}
			
				$q = "SELECT komitent_id, komitent_name, komitent_adresa "
					."FROM komitenti "
					."WHERE komitent_view_status=$vs "
					."ORDER BY komitent_name "
					."LIMIT ".(($page-1)*PAGE_LENGTH).", ".PAGE_LENGTH;
				$res = $this->db->select2($q);
				foreach ($res as $row){
					$ids[] = $row["komitent_id"];
					$names[] = $row["komitent_name"];
					
					$a = $this->adrese->getAll($row["komitent_adresa"]);
					$mesto = $a["lokacija"]["mesto"]["name"];
					if (isset($a["lokacija"]["opstina"])) {
						$mesto .= " / ".$a["lokacija"]["opstina"]["name"];
					}
					if (isset($a["lokacija"]["naselje"])) {
						$mesto .= " / ".$a["lokacija"]["naselje"]["name"];
					}
					$mesta[] = $mesto;
					$adrese[] = $a["ulica"]." ".$a["broj"];
				}
				$this->assign("komid",$ids);
				$this->assign("komname",$names);
				$this->assign("mesto",$mesta);
				$this->assign("adresa",$adrese);
			}else{
				$this->assign("comment_start","<!--");
				$this->assign("comment_end","-->Nema komitenata sa zadatim statusom prikaza.");
			}
			/*foreach ($res as $row){
				$ids[] = $row["komitent_id"];
				$names[] = $row["komitent_name"];
				
				$onclickfunc = "blankTarget('LoadRSDoc(\'komitenti.php?a=displayOne&id=".$row["komitent_id"]."\',\'setContent\')')";
				$clicks[] = '<a href="javascript:void(0)" onclick="'.$onclickfunc.'"><img title="Pogledajte sve podatke o komitentu..." src="gui/record_next.gif" border="0" /></a>';
				//$onclick[] = "LoadRSDoc('komitenti.php?a=displayOne&id=".$row["komitent_id"]."','setContent')";
			}
			$columns = array("šifra","naziv","&nbsp;");
			
			echo '<div class="area" style="max-width:400px;">';
			echo '<div style="float:right">'.count($ids).' komitenata</div>';
			echo '<input type="button" value="osveĹľi" class="refresh" onclick="LoadRSDoc(\'komitenti.php?a=search&t=wrongAddress\',\'setContent\')" /><br clear="all" />';
			
			echo getSimpleTable($columns,array($ids,$names,$clicks),$onclick);
			
			echo '</div>';*/
			
		}else{
			$this->assign("comment_start","<!--");
			$this->assign("comment_end","-->Odaberite status prikaza.");
		}
		
		echo $this->parseTemplate("komitenti/search_view_status.tpl");
	}
	function searchKomitent($field_name,$kword,$list,$addfuncs=null){
		$exact = getFromInput("exact");
		$this->assign("search_kword",$kword);
		if($addfuncs!==null){
			$this->assign("additionalFuncs",$addfuncs);
		}
		if($field_name == "all"){
			$q = "SELECT * FROM komitenti WHERE komitent_name";
			if($exact){
				$q .= "='".addslashes($kword)."' ";
			}else{
				$q .= " LIKE '%".addslashes($kword)."%' ";
			}
			if($exact)
				$q .= "OR komitent_name1='".addslashes($kword)."%' OR komitent_id='".addslashes($kword)."' ORDER BY komitent_name";
			else
				$q .= "OR komitent_name1 LIKE '%".addslashes($kword)."%' OR komitent_id LIKE '%".addslashes($kword)."%' ORDER BY komitent_name"; 
				
		}else{
			if(is_array($field_name)){
				$q = "SELECT * FROM komitenti WHERE ";
				foreach ($field_name as $fn){
					if($exact){
						$q .= "$fn='".addslashes($kword)."' OR ";
					}else{
						$q .= "$fn LIKE '%".addslashes($kword)."%' OR ";
					}
					$orders[] = $fn;
				}
				$q = substr($q,0,strlen($q)-4);
				
				$q .=  " ORDER BY ".implode(",",$orders);
			}else{
				$q = "SELECT * FROM komitenti WHERE $field_name";
				if($exact){
					$q .= "='".addslashes($kword)."' ";
				}else{
					$q .= " LIKE '%".addslashes($kword)."%' ";
				}
				$q .= "ORDER BY $field_name";
			}
		}
		//$q .= " LIMIT ".SEARCH_LIMIT;
		//echo $q;
		$res = $this->db->select2($q);
		if($res){
			$length = count($res);
			$this->assign("search_length",$length);
			$ids = $names = array();
			
			foreach ($res as $komitent){
				$fullname = $komitent["komitent_name1"];
				//echo $fullname."[".strlen($fullname)."]<br />";
				$id = $komitent["komitent_id"];
				$name = $komitent["komitent_name"];
				$adr = $this->adrese->getAll($komitent["komitent_adresa"]);
				
				$adresa = $adr["lokacija"]["mesto"]["name"];
				if(strlen($adr["ulica"])){
					$adresa .= ", ".$adr["ulica"]." ".$adr["broj"];
				}
				// telefoni
				$q = "SELECT telefon,fax FROM komitenti_telefoni WHERE kom_id=".$komitent["komitent_id"]." AND del_id=0 ORDER BY fax";
				$tel = $this->db->select2($q);
				$_telefoni = $_faxovi = array();
				$te="";
				if($tel !== false){
					foreach ($tel as $t){
						if(strlen(trim($t["telefon"]))){
							if($t["fax"]==0){
								$_telefoni[] = $t["telefon"];
							}else{
								$_faxovi[] = $t["telefon"];
							}
						}
					}
					$_telefoni = array_unique($_telefoni);
					$_faxovi = array_unique($_faxovi);
					//$te .= "<br />".implode("-",$_telefoni)."<br />".implode("-",$_faxovi)."<br /><br />";
					if(count($_telefoni)>0)
						$te .= "<br />tel: ".implode(" &middot; ",$_telefoni);
					if(count($_faxovi)>0)
						$te .= "<br />fax: ".implode(" &middot; ",$_faxovi);
				}else{
					$tel = "";
				}
				$info = "<br /><span class=\"info\">$adresa<span style=\"display:block; margin-left:10px;\">".substr($te,6)."</span></span>";
				// delatnosti
				$q = "SELECT DISTINCT komdel_adresa_id FROM komitenti_delatnosti WHERE komdel_kom_id=$id AND komdel_adresa_id !=".$komitent["komitent_adresa"];
				$r = $this->db->select1($q);
				//print_rarray($r);
				if($r[0]){
					foreach ($r as $row){
						$a = $this->adrese->getAll($row[0]);
						$q = "SELECT telefon,fax FROM komitenti_telefoni WHERE kom_id=$id AND adresa=".$row[0]." AND del_id != 0 ORDER BY fax";
						$tels = $this->db->select2($q);
						$tt="";
						$_teldel = $_faxdel = array();
						if($tels !== false){
							foreach ($tels as $t){
								if(strlen(trim($t["telefon"]))){
									if($t["fax"]==0){
										$_teldel[] = $t["telefon"];
									}else{
										$_faxdel[] = $t["telefon"];
									}
								}
							}
							$_teldel = array_unique($_teldel);
							$_faxdel = array_unique($_faxdel);
							
							if(count($_teldel)){
								$tt .= "<br />tel: ".implode(" &middot; ",$_teldel);
							}
							if(count($_faxdel)){
								$tt .= "<br />fax: ".implode(" &middot; ",$_faxdel);
							}
						}
						$aa = $a["lokacija"]["mesto"]["name"];
						if(strlen($a["ulica"])){
							$aa .= ", ".$a["ulica"]." ".$a["broj"];
						}
						$info .= "<span class=\"info\">$aa<span style=\"display:block; margin-left:10px;\">".substr($tt,6)."</span></span>";
					}
				}
				if(is_array($field_name)){
					$q_field_name = implode("-",$field_name);
				}else{
					$q_field_name = $field_name;
				}
				
				switch ($q_field_name){
					case "all":
					case "komitent_name-komitent_name1":
						$rep = '<span class="searchItemHighlight">'.$kword.'</span>';
						$split = preg_split('/('.$kword.')/i',$name,-1,PREG_SPLIT_DELIM_CAPTURE);
						//print_r($split);
						$new = "";
						foreach ($split as $v){
							if(preg_match('/'.$kword.'/i',$v)){
								$new .= '<span class="searchItemHighlight">'.$v.'</span>';
							}else{
								$new .= $v;
							}
						}
						$name = $new;
						$in = "";
						if(stripos($komitent["komitent_name1"],$kword) !== false){
							if(strlen($fullname)){
								$in = '<span class="searchFields"><br />'.$fullname.'</span>';
							}
						}
						$info = "$in".$info;
						break;
					case "komitent_pib-komitent_matbr":
						$in = "<span class=\"searchFields\">";
						if(stripos($komitent["komitent_pib"],$kword) !== false){
							$in .= "<br />PIB: ".$komitent["komitent_pib"];
						}
						if(stripos($komitent["komitent_matbr"],$kword) !== false){
							$in .= "<br />PIB: ".$komitent["komitent_matbr"];
						}
						
						$info = "$in</span>".$info;
						break;
					case "komitent_vlasnik_name-komitent_direktor-komitent_predst":
						$in = "<span class=\"searchFields\">";
						if(stripos($komitent["komitent_vlasnik_name"],$kword) !== false){
							$in .= "<br />Vlasnik: ".$komitent["komitent_vlasnik_name"];
						}
						if(stripos($komitent["komitent_direktor"],$kword) !== false){
							$in .= "<br />Direktor: ".$komitent["komitent_direktor"];
						}
						if(stripos($komitent["komitent_predst"],$kword) !== false){
							$in .= "<br />Predstavnik: ".$komitent["komitent_predst"];
						}
						
						$info = "$in</span>".$info;
						break;
					case "komitent_id":
						//$id = str_replace($kword,'<span class="searchItemHighlight">'.$kword.'</span>',$id);
						break;
				}
				
				$ids[] = $id;
				$names[] = "<strong>$name</strong>$info";
			}
			$this->assign("list_num",$ids);
			$this->assign("list_item",$names);
			
			//print_r($res);
		}else{
			$this->assign("search_length","0 ");
			$this->assign("comment_start","<!--");
			$this->assign("comment_end","-->");
		}
		if($list==1){
			$this->assign("objid",$_GET["objid"]);
			$this->assign("objname",$_GET["objname"]);
			echo $this->parseTemplate("komitenti/search_list_select.tpl");
		}else{
			echo $this->parseTemplate("komitenti/search_list.tpl");
		}
	}
	function searchKomitentKontakt($kword){
		$ids=array();
		$res = array();
		
		$this->assign("search_kword",$kword);
		
		$komitent_polja = array("komitent_id","komitent_name","komitent_adresa","komitent_toll","komitent_vlasnik_name","komitent_direktor","komitent_direktor_tel","komitent_predst","komitent_predst_tel");
		
		//komitenti
		$q = "SELECT DISTINCT ".implode(", ",$komitent_polja)." FROM komitenti WHERE "
			."komitent_vlasnik_name like '%$kword%' OR "
			."komitent_direktor like '%$kword%' OR "
			."komitent_direktor_tel like '%$kword%' OR "
			."komitent_predst like '%$kword%' OR "
			."komitent_predst_tel like '%$kword%' OR "
			."komitent_toll like '%$kword%' "
			."ORDER BY komitent_name";
		$res1 = $this->db->select2($q);
		//echo $q;
		$i=0;
				
		if($res1[0]){
			foreach ($res1 as $k=>$v){
				$id = $v["komitent_id"];
				$ids[] = $id;
				
				foreach ($komitent_polja as $polje){
					$res[$id][$polje] = $v[$polje];
				}
				
				// tel-fax
				$tels = $this->db->select2("SELECT DISTINCT telefon,fax FROM komitenti_telefoni WHERE kom_id=".$v["komitent_id"]);
				if($tels[0]){
					foreach ($tels as $tel){
						if($tel["fax"]){
							$res[$id]["fax"][] = $tel["telefon"];
						}else{
							$res[$id]["tel"][] = $tel["telefon"];
						}
					}
				}
				// email
				$emails = $this->db->select2("SELECT DISTINCT email FROM komitenti_emails WHERE kom_id=".$v["komitent_id"]);
				if($emails[0]){
					foreach ($emails as $email){
						$res[$id]["email"][] = $email["email"];
					}
				}
				// web
				$webs = $this->db->select2("SELECT DISTINCT web FROM komitenti_webs WHERE kom_id=".$v["komitent_id"]);
				if($webs[0]){
					foreach ($webs as $web){
						$res[$id]["web"][] = $web["web"];
					}
				}
			}
		}
		
		// komitenti_telefoni
		$q = "SELECT DISTINCT telefon, ".implode(", ",$komitent_polja).", fax "
			."FROM  komitenti, komitenti_telefoni "
			."WHERE komitent_id=kom_id "
			."AND telefon like '%$kword%' ";
			foreach ($ids as $id){
				$q .= "AND komitent_id!=$id ";
			}
			//$q .= "GROUP BY komitent_id";
		$res1 = $this->db->select2($q);
		if($res1[0]){
			foreach ($res1 as $row){
				$id = $row["komitent_id"];
				$ids[] = $id;
				$res[$id]["komitent_id"] = $row["komitent_id"];
				$res[$id]["komitent_name"] = $row["komitent_name"];
				$res[$id]["komitent_adresa"] = $row["komitent_adresa"];
				$res[$id]["komitent_toll"] = $row["komitent_toll"];
				$res[$id]["komitent_vlasnik_name"] = $row["komitent_vlasnik_name"];
				$res[$id]["komitent_direktor"] = $row["komitent_direktor"];
				$res[$id]["komitent_direktor_tel"] = $row["komitent_direktor_tel"];
				$res[$id]["komitent_predst"] = $row["komitent_predst"];
				$res[$id]["komitent_predst_tel"] = $row["komitent_predst_tel"];
				
				
				if($row["fax"]==1){
					$res[$id]["fax"][] = $row["telefon"];
				}else{
					$res[$id]["tel"][] = $row["telefon"];
				}
			}
		}
		
		// komitenti_emails
		$q = "SELECT DISTINCT email, ".implode(", ",$komitent_polja)." "
			."FROM  komitenti, komitenti_emails "
			."WHERE komitent_id=kom_id "
			."AND email like '%$kword%' ";
			foreach ($ids as $id){
				$q .= "AND komitent_id!=$id ";
			}
			//$q .= "GROUP BY komitent_id";
		$res1 = $this->db->select2($q);
		if($res1[0]){
			foreach ($res1 as $row){
				$id = $row["komitent_id"];
				$ids[] = $id;
				$res[$id]["komitent_id"] = $row["komitent_id"];
				$res[$id]["komitent_name"] = $row["komitent_name"];
				$res[$id]["komitent_adresa"] = $row["komitent_adresa"];
				$res[$id]["komitent_vlasnik_name"] = $row["komitent_vlasnik_name"];
				$res[$id]["komitent_direktor"] = $row["komitent_direktor"];
				$res[$id]["komitent_direktor_tel"] = $row["komitent_direktor_tel"];
				$res[$id]["komitent_predst"] = $row["komitent_predst"];
				$res[$id]["komitent_predst_tel"] = $row["komitent_predst_tel"];
				$res[$id]["komitent_toll"] = $row["komitent_toll"];
				$res[$id]["email"][] = $row["email"];
			}
		}
		
		// komitenti_webs
		$q = "SELECT DISTINCT web, ".implode(", ",$komitent_polja)." "
			."FROM  komitenti, komitenti_webs "
			."WHERE komitent_id=kom_id "
			."AND web like '%$kword%' ";
			foreach ($ids as $id){
				$q .= "AND komitent_id!=$id ";
			}
			//$q .= "GROUP BY komitent_id";
		$res1 = $this->db->select2($q);
		if($res1[0]){
			foreach ($res1 as $row){
				$id = $row["komitent_id"];
				$ids[] = $id;
				$res[$id]["komitent_id"] = $row["komitent_id"];
				$res[$id]["komitent_name"] = $row["komitent_name"];
				$res[$id]["komitent_adresa"] = $row["komitent_adresa"];
				$res[$id]["komitent_toll"] = $row["komitent_toll"];
				$res[$id]["komitent_vlasnik_name"] = $row["komitent_vlasnik_name"];
				$res[$id]["komitent_direktor"] = $row["komitent_direktor"];
				$res[$id]["komitent_direktor_tel"] = $row["komitent_direktor_tel"];
				$res[$id]["komitent_predst"] = $row["komitent_predst"];
				$res[$id]["komitent_predst_tel"] = $row["komitent_predst_tel"];
				$res[$id]["web"][] = $row["web"];
			}
		}
		
		if(is_array($res) && count($res)>0){
			$res = $this->sortRes($res,"komitent_name");
			$this->assign("search_length",count($res));
			
			//echo '<div class="area" style="min-width:300px">';print_rarray($res);echo '</div><br clear="all" />';
			
			foreach ($res as $row){
				$sifre[] = $row["komitent_id"];
				$adr = $this->adrese->getAll($row["komitent_adresa"]);
				
				$name = $row["komitent_name"];
				
				$info = '<span class="info"><br />'.$adr["lokacija"]["mesto"]["name"];
				if($adr["ulica"]){
					$info .= ", ".$adr["ulica"]." ".$adr["broj"];
				}
				
				if($row["komitent_vlasnik_name"]){
					$info .= "<br />vlasnik: ".$row["komitent_vlasnik_name"];
				}
				if($row["komitent_direktor"]){
					$info .= "<br />direktor: ".$row["komitent_direktor"];
					if($row["komitent_direktor_tel"]){
						$info .= ", ".$row["komitent_direktor_tel"];
					}
				}
				if($row["komitent_predst"]){
					$info .= "<br />predstavnik: ".$row["komitent_predst"];
					if($row["komitent_predst_tel"]){
						$info .= ", ".$row["komitent_predst_tel"];
					}
				}
				
				if($row["komitent_toll"]){
					$info .= "<br />".$row["komitent_toll"];
				}
				
				if($row["tel"]){
					$info .= "<br />tel: ".implode(" &middot; ",$row["tel"]);
				}
				
				if($row["fax"]){
					$info .= "<br />fax: ".implode(" &middot; ",$row["fax"]);
				}
				
				if($row["email"]){
					$info .= "<br />e-mail: ".implode(" &middot; ",$row["email"]);
				}
				
				if($row["web"]){
					$info .= "<br />web: ".implode(" &middot; ",$row["web"]);
				}
				
				$info .= '</span>';
				$items[] = $name."$info";
			}
			$this->assign("list_num",$sifre);
			$this->assign("list_item",$items);
		}else{
			$this->assign("search_length","0");
			$this->assign("comment_start","<!--");
			$this->assign("comment_end","-->");
			$this->assign("message","No results");
		}
				
		echo $this->parseTemplate("komitenti/search_list.tpl");
	}
	function searchKomitentAdresa($kword){
		$this->assign("search_kword",$kword);
		
		$last_space = strrpos($kword," ");
		if($last_space>0){
			$ul=substr($kword,0,$last_space);
			$br=substr($kword,$last_space+1);
		}else{
			$ul=$kword;
			$br="";
		}
		//echo "<p>$ul<br />$br</p>";
		
		$q = "SELECT a.adresa_id "
			."FROM adrese a, ulice u, lokacije l "
			."WHERE a.adresa_lid=l.lid "
			."AND a.adresa_ul_id=u.ulica_id "
			."AND ("
			."l.lok_naziv LIKE '%$kword%' OR "
			."u.ulica_ime LIKE '%$kword%' OR "
			."(CONCAT(u.ulica_ime,a.adresa_broj)) LIKE '%$ul$br%'"
			.") ORDER BY adresa_id";
		//echo $q;
		
		$adrese = $this->db->select1($q);
		
		$nums = $items = array();
		if($adrese[0]){
			
			$allres = $this->searchKomiteniByAddress($adrese);
			$allres = $this->sortRes($allres);
			foreach ($allres as $k=>$v){
				
				$ids[] = $v["komitent_id"];
				$name = $v["komitent_name"];
				
				$adr = $this->adrese->getAll($v["komitent_adresa"]);
				$info = '<span class="searchFields">'.$adr["lokacija"]["mesto"]["name"];
				if(strlen(trim($adr["ulica"]))){
					$info .= ", ".$adr["ulica"]." ".$adr["broj"];
				}
				$info .= "</span>";
				
				// ostale adrese KOMITENTI
				$nadjene_adr = array();
				$q = "SELECT komitent_adresa FROM komitenti WHERE komitent_id=".$v["komitent_id"]." AND komitent_adresa!=".$v["komitent_adresa"];
				$adr_res_rest = $this->db->select1($q);
				if($adr_res_rest[0]){
					foreach ($adr_res_rest as $adresa){
						$nadjene_adr[] = $adresa[0];
						$adr = $this->adrese->getAll($adresa[0]);
						$info .= "<br />".$adr["lokacija"]["mesto"]["name"];
						if(strlen(trim($adr["ulica"]))){
							$info .= ", ".$adr["ulica"]." ".$adr["broj"];
						}
					}
				}
				
				// ostale adrese KOMITENTI_DELATNOSTI
				$q = "SELECT komdel_adresa_id FROM komitenti_delatnosti WHERE komdel_kom_id=".$v["komitent_id"]." AND komdel_adresa_id!=".$v["komitent_adresa"];
				foreach ($nadjene_adr as $nadjena){
					$q .= " AND komdel_adresa_id!=$nadjena";
				}
				$adr_res_rest = $this->db->select1($q);
				if($adr_res_rest[0]){
					foreach ($adr_res_rest as $adresa){
						$adr = $this->adrese->getAll($adresa[0]);
						$info .= "<br />".$adr["lokacija"]["mesto"]["name"];
						if(strlen(trim($adr["ulica"]))){
							$info .= ", ".$adr["ulica"]." ".$adr["broj"];
						}
					}
				}
				
				$names[] = $name.'<br /><span class="info">'.$info.'</span>';
			}
			
			$this->assign("search_length",count($ids));
			$this->assign("list_num",$ids);
			$this->assign("list_item",$names);
		}
		
		if(count($nums)>0){
			$this->assign("search_length","0 ");
			$this->assign("comment_start","<!--");
			$this->assign("comment_end","-->");
		}
		
		
		
		echo $this->parseTemplate("komitenti/search_list.tpl");
	}
	function searchKomitentZR($kword){
		$q = "SELECT komitent_id, komitent_name, ziro_value, banka_name "
			."FROM komitenti k, komitenti_ziro_racuni kzr, banke b "
			."WHERE k.komitent_id=kzr.ziro_komitent_id "
			."AND kzr.ziro_banka_id=b.banka_id "
			."AND kzr.ziro_value like '%$kword%' "
			."ORDER BY komitent_name";
		$res = $this->db->select2($q);
		$this->assign("search_kword",$kword);
		if($res !== false){
			$search = array();
			foreach ($res as $row){
				$id = $row["komitent_id"];
				$name = $row["komitent_name"];
				$info = '<br /><span class="info">'.$row["banka_name"].': <span class="searchFields">'.$row["ziro_value"].'</span></span>';
				$search[$id]["name"] = $name;
				$search[$id]["info"][] = $info;
			}
			
			foreach ($search as $k=>$v){
				$ids[] = $k;
				$names[] = $v["name"].implode("",$v["info"]);
			}
			
			$this->assign("search_length",count($res));
			$this->assign("list_num",$ids);
			$this->assign("list_item",$names);
		}else{
			$this->assign("search_length","0");
		}
		echo $this->parseTemplate("komitenti/search_list.tpl");
	}
	function searchKomitentKeyword($kword){
		$q = "SELECT DISTINCT komitent_id, komitent_name, profil_text "
			."FROM komitenti, profili "
			."WHERE komitent_id=profil_kom_id "
			."AND profil_text like '%$kword%' "
			."ORDER BY komitent_name LIMIT 0,50";
		$res = $this->db->select2($q);
		
		$list = array();
		if($res !== false){
			foreach ($res as $red){
				$list[$red["komitent_id"]]["name"] = $red["komitent_name"];
				$list[$red["komitent_id"]]["profil"] = $red["profil_text"];
			}
		}
		$ids = array_keys($list);
		
		$q = "SELECT DISTINCT komdel_kom_id, komitent_name, profil_text "
			."FROM komitenti, komitenti_delatnosti, profili "
			."WHERE komdel_kom_id=komitent_id "
			."AND komdel_kom_id=profil_kom_id "
			."AND profil_text LIKE '%$kword%' "
			."AND (";
		foreach ($ids as $id){
			$q .= "komdel_kom_id!=$id AND ";
		}
		$q = substr($q,0,strlen($q)-4).") ";
			
		$q .= "ORDER BY komitent_name ";
		
		$res = $this->db->select2($q);
		if($res !== false){
			foreach ($res as $red){
				$list[$red["komdel_kom_id"]]["name"] = $red["komitent_name"];
				$list[$red["komdel_kom_id"]]["profil"] = $red["profil_text"];
			}
		}
		$ids=$names=array();
		foreach ($list as $id=>$val){
			$ids[] = $id;
			$index = stripos($val["profil"],$kword);
			$start = $index>10?$index-10:0;
			$info = substr($val["profil"],$start,strlen($kword)+10);
			$names[] = $val["name"]."<br /><span class=\"info\">...$info...</span>";
		}
		$this->assign("search_kword",$kword);
		$this->assign("search_length",count($list));
		$this->assign("list_num",$ids);
		$this->assign("list_item",$names);
		echo $this->parseTemplate("komitenti/search_list.tpl");
	}
	
	//----------------------------------------------------------------------------
	
	function showAdvanceSearch(){
		
		$this->assign("attrib_id",array_keys($this->komitentAttributes));
		$this->assign("attrib_name",array_values($this->komitentAttributes));
		
		$gradovi = $this->get_Lokacije(1);
			$this->assign("grad_id",$gradovi["polje_id"]);
			$this->assign("grad_name",$gradovi["polje_ime"]);
		$lokops = $this->get_Lokacije(2);
			$this->assign("lokops_id",$lokops["polje_id"]);
			$this->assign("lokops_name",$lokops["polje_ime"]);
			$this->assign("lokops_parent",$lokops["polje_parent"]);
		$naselja = $this->get_Lokacije(3);
			$this->assign("naselje_id",$naselja["polje_id"]);
			$this->assign("naselje_name",$naselja["polje_ime"]);
			$this->assign("naselje_parent",$naselja["polje_parent"]);
		
		$polja = $this->get_Kategorije();
			$this->assign("kat_id",$polja["id"]);
			$this->assign("kat_name",$polja["name"]);
			
		$polja = $this->get_Delatnosti();
			$this->assign("del_id",$polja["id"]);
			$this->assign("del_name",$polja["name"]);
			$this->assign("delkat_id",$polja["kategorija"]);
		
		$polja = $this->get_Kampanje();
			$this->assign("kampanja_id",$polja["id"]);
			$this->assign("kampanja_ime",$polja["name"]);
		
		
		$style = array(
			"br" => ' style="clear:both; display:block;"'
		);
		$komitent_adresa = getAdresaHtml("","sve","_komitent",$style,1);
		$this->assign("adresa",$komitent_adresa);
		
		$ugokam_adresa = getAdresaHtml("","sve","_ugokam",$style,1);
		$this->assign("adresa_ugokam",$ugokam_adresa);
		
		$polja = $this->get_ViewStatus();//print_rarray($polja);
			$this->assign("vsid",$polja["id"]);
			$this->assign("vsname",$polja["name"]);
		
		echo $this->parseTemplate("komitenti/advance_search.tpl");
	}
	function advanceSearch($post){
		if(isset($post["submitted"])){
			
			$directDownload = intval(getFromInput("directDownload"));
			
			$page = getFromInput("page");
			$page = $page>0?$page:1;
			$start = ($page-1)*SEARCH_LIMIT;
			
			switch ($post["sort"]){
				default:
				case "1":
					$sort = "komitent_name";
					break;
				case "2":
					$sort = "ulica_ime, sort_broj";
					break;
			}
			
			// BEZ VIEW STATUS
			$vs = $this->get_ViewStatus();
			$bVS = array();
			foreach ($vs["id"] as $id){
				$_vs = getFromInput("vs_$id");
				if ($_vs>0) {
					$bVS[] = $id;
				}
			}
			
			// BEZ KAMPANJA
			$bKampanjaLength = (int)getFromInput("bez_kampanja_length");
			$bKampanja = array();
			for ($i=1; $i<=$bKampanjaLength; $i++){
				$tmp = getFromInput("bez_kampanja_$i");
				if ($tmp>0 && !in_array($tmp,$bKampanja)) {
					$bKampanja[] = $tmp;
				}
			}
			
			// BEZ ZAKAZANOG SASTANKA
			$bSastanak = null;
			$bSastanakOD = getFromInput("bez_sastanak_od");
			$bSastanakDO = getFromInput("bez_sastanak_do");
			if (preg_match('/^\d{1,2}\.\d{1,2}\.\d{2,4}$/',$bSastanakOD) && preg_match('/^\d{1,2}\.\d{1,2}\.\d{2,4}$/',$bSastanakDO)) {
				$bSastanak = array(
					"od" => date2int($bSastanakOD),
					"do" => date2int($bSastanakDO)
				);
			}
			
			
			$ra = $_SERVER['REMOTE_ADDR'];
			if(strlen($ra)){
				$tmp = explode(".",$ra,4);
				$last = trim($tmp[3]);
				if($last < 200){
					$local = intval($last)+100;
				}else{
					$local = $last;
				}
				//echo $local;
			}
			
			$mesid = $post["grad_komitent"];
			$lopsid = $post["lok_opstina_komitent"];
			$nasid = $post["naselje_komitent"];
			
			$_lopstine = $post["lopstine"];
			$_naselja = $post["naselja"];
			
			//print_rarray($post);
			$naselja = preg_match('/;/',$post["naselja"])?explode(";",$post["naselja"]):array();
			$lopstine = preg_match('/;/',$post["lopstine"])?explode(";",$post["lopstine"]):array();

			
			$ulid = $post["ulica_id_komitent"];
			$broj = $post["broj_komitent"];
			
			$delid = $post["delatnost"];
			
			if($mesid<1 && $lopsid<1 && $nasid<1 && $ulid<1 && $broj<1){
				echo "<h2 style=\"color:red\">Morate odabrati mesto, lokalnu opštinu, naselje ili ulicu.</h2>";
			}else{
				if($nasid>0){
					$lid = $nasid;
					$ltip = 3;
				}else{
					if($lopsid>0){
						$lid = $lopsid;
						$ltip = 2;
					}else{
						$lid = $mesid;
						$ltip = 1;
					}
				}
				$lids = array();
				$st = "lokacija: <i>".$this->db->getOne("SELECT lok_naziv FROM lokacije WHERE lid=$lid LIMIT 1")."</i>";
				$q = "SELECT adresa_id FROM adrese WHERE (adresa_lid=$lid";
				//echo "$ltip $lid";
				if($lid>0){
					$lids = $this->getLIDS($ltip,$lid);
				}
				$q_adresa = "(adresa_lid=$lid";
				if (count($lids)) {
					$lids = array_unique($lids);
					foreach ($lids as $l){
						$q_adresa .= " OR adresa_lid=$l";
					}
				}
				$q .= ")";
				$q_adresa .= ")";
				if($ulid>0){
					$q_adresa .= " AND adresa_ul_id=$ulid";
					$st .= ", ulica: <i>".$this->db->getOne("SELECT ulica_ime FROM ulice WHERE ulica_id=$ulid LIMIT 1")."</i>";
				}
				if($broj>0){
					$q_adresa .= " AND adresa_broj LIKE '$broj%'";
					$st .= ", broj: <i>$broj</i>";
				}
				
				$adrese = array();
				$ids = array();
				$_ids = array();
				$ukupno=0;
				//-----------------------
				// komitenti_delatnosti
				//-----------------------
				$q_select = "SELECT DISTINCT k.komitent_id as komid, k.komitent_name, k.komitent_direktor, k.komitent_direktor_tel, kd.komdel_adresa_id as komitent_adresa , ulica_ime,adresa_broj";
				

				/*********************************
				 	SORT BY address HACK
				 	
				 	if last char of address is number,
				 	then add sign `-` in the end of address
				 	and than sort it
				 ***************************************/
				$padd_length = 7;				
				$q_select .= ", CASE WHEN ASCII(RIGHT(adresa_broj,1))>47 AND ASCII(RIGHT(adresa_broj,1))<58 THEN LPAD(CONCAT(adresa_broj,'-'),$padd_length,'0') ELSE LPAD(adresa_broj,$padd_length,'0')	END as sort_broj";
				
				
				$q_from = "FROM komitenti k, komitenti_delatnosti kd, adrese, ulice ";
				$q_where = "WHERE k.komitent_view_status != 4 "
						  ."AND k.komitent_id=kd.komdel_kom_id "
						  ."AND komdel_adresa_id=adresa_id "
						  ."AND adrese.adresa_ul_id=ulice.ulica_id ";
					if($delid>0){
						$q_where .= "AND komdel_del_id=$delid ";
						$st .= ", delatnost: <i>".$this->db->getOne("SELECT delatnost_ime FROM delatnosti WHERE delatnost_id=$delid LIMIT 1")."</i>";
					}
					
					$q_where .= " AND ($q_adresa)";
				
				if (count($bVS)>0){
					$q_where .= " AND (1";
					foreach ($bVS as $b){
						$q_where .= " AND k.komitent_view_status!=$b";
					}
					$q_where .= ")";
				}
				
				if ($directDownload) {
					$this->advanceSearchDownload("$q_select $q_from $q_where ORDER BY $sort");
					die();
				}
				
				$ukupno_del = $this->db->select1("$q_select $q_from $q_where");
				$this->assign("filter_query","$q_select $q_from $q_where");
				$q = "$q_select $q_from $q_where ORDER BY $sort LIMIT $start,".SEARCH_LIMIT;
				
				//echo $q;
				$res_del = $this->db->select2($q);
				
				if($res_del){
					$ukupno += count($ukupno_del);
					if(is_array($res)){
						$all_res = array_merge($res,$res_del);
					}else{
						$all_res = $res_del;
					}
				}else{
					$all_res = $res;
				}
				
				$this->assign("search_term",$st);
				
				if($all_res){
					
					$num_pages = bcdiv($ukupno,SEARCH_LIMIT,0);
					if ($ukupno%SEARCH_LIMIT) {
						$num_pages++;
					}
					//echo "page: $page";
					for ($i=1; $i<=$num_pages; $i++){
						$pages[] = $i;
						if ($i==$page) {
							$pages_selected[] = ' id="current"';
						}else{
							$pages_selected[] = '';
						}
					}
					
					foreach ($all_res as $k=>$komitent){
						$ok=true;
						if ($bSastanak) {
							$q = "SELECT DISTINCT 1"
								." FROM rokovnik r, rokovnik_result rr"
								." WHERE r.id=rr.rokovnik_id"
								." AND rr.type=3"
								." AND r.komitent_id=".$komitent["komid"]
								." AND rr.time>=".$bSastanak["od"]
								." AND rr.time<=".(intval($bSastanak["do"])+(60*60*24))
								." LIMIT 1";
							$imasastanak = $this->db->getOne($q);
							if ($imasastanak>0) {
								$ok=false;
							}
						}
						if (count($bKampanja)>0) {
							
							/*$sql = "SELECT 1 FROM komitenti_kampanje "
								  ."WHERE komitent_id=".$komitent["komid"]." "
								  ."AND kampanja_id IN(".implode(",",$bKampanja).") LIMIT 1";*/
								  
							$sql = "SELECT 1 FROM ugovori_stavke "
								  ."WHERE komitent=".$komitent["komid"]." "
								  ."AND kampanja IN(".implode(",",$bKampanja).") LIMIT 1";
							$imakampanju = $this->db->getOne($sql);
							if ($imakampanju) {
								$ok=false;
							}
						}
						
						
						
						if($ok){
							$num[] = (($page-1)*SEARCH_LIMIT)+$k+1;
							$adr = $this->adrese->getAll($komitent["komitent_adresa"]);
							$tels = $this->db->select2("SELECT DISTINCT telefon, fax FROM komitenti_telefoni WHERE kom_id=".$komitent["komid"]);
							$emails = $this->db->select2("SELECT DISTINCT email FROM komitenti_emails WHERE kom_id=".$komitent["komid"]);
							
							$zrs = $this->db->select2("SELECT DISTINCT ziro_value, banka_name FROM komitenti_ziro_racuni, banke WHERE komitenti_ziro_racuni.ziro_banka_id=banke.banka_id AND komitenti_ziro_racuni.ziro_komitent_id=".$komitent["komid"]);
							//echo "SELECT DISTINCT ziro_value, banka_name FROM komitenti_ziro_racuni, banke WHERE komitenti_ziro_racuni.ziro_banka_id=banke.banka_id AND komitenti_ziro_racuni.ziro_komitent_id=".$komitent["komitent_id"]."<br />";
							
							$dels = $this->db->select2("SELECT DISTINCT delatnost_ime FROM komitenti_delatnosti kd, delatnosti d WHERE kd.komdel_del_id=d.delatnost_id AND kd.komdel_kom_id=".$komitent["komid"]);
							
							
							$faxs = $telss = $mails = $zir = $delas = array();
							if($tels[0]){
								foreach ($tels as $tel){
									if($tel["fax"]){
										$faxs[] = $tel["telefon"];
									}else{
										$telss[] = '<a target="sophone" onclick="event.stopPropagation()" href="http://192.168.5.2/gw/call.php?l='.$local.'&r='.preg_replace('/[^\d]/',"",$tel["telefon"]).'">'.$tel["telefon"].'</a>';
									}
								}
							}
							//print_r($telss);
							if($emails[0]){
								foreach ($emails as $mail){
									$mails[] = $mail["email"];
								}
							}
							if($zrs[0]){
								foreach ($zrs as $zr){
									$zir[] = $zr["banka_name"].":<br />".$zr["ziro_value"];
								}
							}
							//echo ($komitent["komitent_id"])." ";
							//print_rarray($zir);
							
							if($dels[0]){
								foreach ($dels as $d){
									$delas[] = $d["delatnost_ime"];
								}
							}
							
							$ids[] = $komitent["komid"];
							$names[] = $komitent["komitent_name"];
							$names_url[] = urlencode($komitent["komitent_name"]);
							$adrs[] = $adr["ulica"]." ".$adr["broj"]."<br />".$adr["lokacija"]["mesto"]["name"];
							$dirs[] = $komitent["komitent_direktor"];
							$telefon[] = @implode("<br />",$telss);
							$fax[] = @implode("<br />", $faxs);
							$email[] = @implode("<br />",$mails);
							$ziros[] = @implode("<br /><br />",$zir);
							$delatnost[] = @implode("<br />",$delas);
						}else{
							$ukupno--;
						}
					}
					$this->assign("page",$pages);
					$this->assign("current_page",$pages_selected);
					$this->assign("info",$ukupno);
					$this->assign("num",$num);
					$this->assign("id",$ids);
					$this->assign("name",$names);
					$this->assign("name_url",$names_url);
					$this->assign("adresa",$adrs);
					$this->assign("direktor",$dirs);
					$this->assign("tel",$telefon);
					$this->assign("fax",$fax);
					$this->assign("email",$email);
					$this->assign("ziro",$ziros);
					$this->assign("del",$delatnost);
					
					echo $this->parseTemplate("komitenti/adv_search_table.tpl");
				}else{
					echo "No results ";
				}
			}
			
		}
	}
	function advanceSearchKampanjeUgovori(){
		$page = getFromInput("page"); $page = $page>0?$page:1;
		$grad = getFromInput("grad_ugokam");
		$lops = getFromInput("lok_opstina_ugokam");
		$nase = getFromInput("naselje_ugokam");
		$ulica = getFromInput("ulica_id_ugokam");
		$broj = getFromInput("broj_ugokam");
		$sastanak_od = date2int(getFromInput("ugokam_sastanak_od"));
		$sastanak_do = date2int(getFromInput("ugokam_sastanak_do"));
		
		$sa_kamid = getFromInput("kampanja_sa");
		list($sa_kamid) = removeZeroVals(explode(";",$sa_kamid));
		
		$bez_kamid = getFromInput("kampanja_bez");
		list($bez_kamid) = removeZeroVals(explode(";",$bez_kamid));
		
		$filter_query = "kampanja_sa=".@implode(";",$sa_kamid)
					   ."&kampanja_bez=".@implode(";",$bez_kamid)
					   ."&grad_ugokam=$grad"
					   ."&lok_opstina_ugokam=$lops"
					   ."&naselje_ugokam=$nase"
					   ."&ulica_id_ugokam=$ulica"
					   ."&broj_ugokam=$broj"
					   ."&ugokam_sastanak_od=$sastanak_od"
					   ."&ugokam_sastanak_do=$sastanak_do";
		$this->assign("filter_query",$filter_query);
		
		
		
		$q_select = "SELECT DISTINCT komitent_id, komitent_name, komdel_adresa_id, ulica_ime, adresa_broj, lok_naziv, kampanja ";
		$q_from = "FROM ugovori_stavke, komitenti, komitenti_delatnosti, adrese, ulice, lokacije ";
		$q_where = "WHERE komdel_kom_id=komitent "
				  ."AND komitenti_delatnosti.komdel_kom_id=komitenti.komitent_id "
				  ."AND komdel_adresa_id=adresa_id "
				  ."AND adresa_ul_id=ulica_id "
				  ."AND adresa_lid=lid ";
		
		if (count($sa_kamid)>0) {
			$q_where .= "AND (0";
			foreach ($sa_kamid as $kamid){
				$q_where .= " OR kampanja=$kamid";
			}
			$q_where .= ")";
		}
		
		if ($grad>0) {
			if ($lops<1 && $ulica<1) {
				//die("Pored grada morate odabrati i ulicu ili lokalnu opštinu.");
			}
			if ($nase>0) {
				$lid=$nase;
				$type=3;
			}else if ($lops>0) {
				$lid=$lops;
				$type=2;
			}else{
				$lid=$grad;
				$type=1;
			}
			$children = $this->getLIDS($type,$lid);
			$q_where .= " AND (adresa_lid=$lid";
			foreach ($children as $l){
				$q_where .= " OR adresa_lid=$l";
			}
			$q_where .= ")";
		}
		if ($ulica>0) {
			$q_where .= " AND adresa_ul_id=$ulica";
		}
		if (strlen(trim($broj))>0) {
			$q_where .= " AND adresa_broj LIKE '%$broj%'";
		}
		
		$ukupno = $this->db->select1("$q_select $q_from $q_where");
		$ukupno = $ukupno!==false?count($ukupno):0;
		$this->assign("ukupno",sprintf("%s",$ukupno));
		
		$numpages = bcdiv($ukupno,PAGE_LENGTH,0);
		if ($ukupno%PAGE_LENGTH>0) {
			$numpages++;
		}
		
		for ($i=0; $i<$numpages; $i++){
			$pages[$i] = $i+1;
			if ($pages[$i]==$page) {
				$page_cur[$i] = " id=\"current\"";
			}else{
				$page_cur[$i] = "";
			}
		}
		$this->assign("page",$pages);
		$this->assign("current_page",$page_cur);
		
		
		$start = ($page-1)*PAGE_LENGTH;
		$q_order = "ORDER BY lok_naziv, ulica_ime, adresa_broj, komitent_name";
		$q_limit = "LIMIT $start,".PAGE_LENGTH;
	
		$q = "$q_select $q_from $q_where $q_order $q_limit";
		$res = $this->db->select2($q);
		
		if ($res !== false) {
			foreach ($res as $k=>$row){
				$komids[$k] = $row["komitent_id"];
				$komnames[$k] = $row["komitent_name"];
				$mesto[$k] = $row["lok_naziv"];
				$adresa[$k] = $row["ulica_ime"]." ".$row["adresa_broj"];
				
				$kampanja_id[$k] = $row["kampanja"];
				$kampanja_name[$k] = $this->db->getOne("SELECT kampanja_naziv FROM kampanje WHERE kampanja_id=".$row["kampanja"]);
				
				
				//----------------------------
				//		BEZ
				//----------------------------
				$bez=false;
				
				// BEZ KAMPANJE
				if (count($bez_kamid)>0) {
					$q1 = "SELECT 1 FROM ugovori_stavke WHERE komitent=".$row["komitent_id"]." AND (0";
					foreach ($bez_kamid as $kamid){
						$q1 .= " OR kampanja=$kamid";
					}
					$q1 .= ")";
					$ima = intval($this->db->getOne($q1));
					
					if ($ima>0) {
						$bez=true;
					}
				}
				
				// BEZ SASTANKA
				$day = 60*60*24;
				if (!$bez && ($sastanak_od>0 || $sastanak_do>0)) {
					$q1 = "SELECT 1 FROM rokovnik r, rokovnik_result rr "
						 ."WHERE r.id=rr.rokovnik_id "
						 ."AND rr.type=3 "
						 ."AND r.komitent_id=".$row["komitent_id"]." ";
					if ($sastanak_od>0) {
						$q1 .= "AND rr.time>=$sastanak_od ";
						if ($sastanak_do>0) {
							$q1 .= "AND rr.time<=".($sastanak_do+$day)." ";
						}
					}else{
						$q1 .= "AND rr.time<=$sastanak_do".($sastanak_do+$day)." ";
					}
					
					$ima = intval($this->db->getOne($q1));
					//echo $q1; var_dump($ima);
					if ($ima) {
						$bez=true;
					}
				}
				
				$bezs[$k] = $bez?"bez":"";
				
			}
			$this->assign("komitent_id",$komids);
			$this->assign("komitent_name",$komnames);
			$this->assign("mesto",$mesto);
			$this->assign("adresa",$adresa);
			$this->assign("kampanja_id",$kampanja_id);
			$this->assign("kampanja",$kampanja_name);
			$this->assign("bez",$bezs);
		}else{
			$this->assign("comment_start","<!--");
			$this->assign("comment_end","-->");
		}
		
		echo $this->parseTemplate("komitenti/adv_search_table_ugokam.tpl");
	}
	function advanceSearchProfile(){
		$kword = readValFromInput("kword");
		$page = getFromInput("page");
		$page = $page>0?$page:1;
		$this->assign("search_term","tekst profila: <i>$kword</i>");
		$words = array();
		if(strpos($kword," ")>0){
			$words = explode(" ",$kword);
		}
		
		$grad = getFromInput("komprofile_mesto");
		$lokops = getFromInput("komprofile_lokops");
		$naselje = getFromInput("komprofile_naselje");
		
		// filter assign
		$this->assign("filter_kword",$kword);
		$this->assign("filter_grad",$grad);
		$this->assign("filter_lokops",$lokops);
		$this->assign("filter_naselje",$naselje);
		
		$lid = $naselje>0?$naselje:($lokops>0?$lokops:$grad);
		
		$q_select = "SELECT profil_kom_id as komid, komitent_name as komname, profil_text, profil_lang, komdel_adresa_id";
		$q_from = "FROM komitenti, komitenti_delatnosti, adrese, profili";
		$q_where = "WHERE komitenti.komitent_id=profil_kom_id";
		$q_where .= " AND komitenti_delatnosti.komdel_adresa_id=adrese.adresa_id";
		$q_where .= " AND komitenti.komitent_id=komitenti_delatnosti.komdel_kom_id";
		$q_where .= " AND profili.profil_text LIKE '%$kword%'";
		
		if($lid>0){
			//$q_select .= ", komitent_adresa, komdel_adresa_id ";
			//$q_from .= ", komitenti_delatnosti, adrese";
			$q_where .= " AND (adresa_lid=$lid";
			$children1 = $this->db->select1("SELECT lid FROM lokacije WHERE lok_parent=$lid");
			if ($children1 !== false) {
				foreach ($children1 as $row){
					$q_where .= " OR adresa_lid=".$row[0];
					$children2 = $this->db->select1("SELECT lid FROM lokacije WHERE lok_parent=".$row[0]);
					if ($children2 !== false) {
						foreach ($children2 as $row2){
							$q_where .= " OR adresa_lid=".$row2[0];
						}
					}
				}
			}
			$q_where .= ")";
		}
		
		$q = "$q_select $q_from $q_where GROUP BY profili.profil_kom_id ORDER BY komname";
		$ukupno = count($this->db->select1($q));
		$q .= " LIMIT ".($page-1)*PAGE_LENGTH.",".PAGE_LENGTH;
		$res = $this->db->select2($q);
		//print_rarray($res);die();
		if($res !== false){
			
			$numpages = bcdiv($ukupno,PAGE_LENGTH,0);
			if ($ukupno%PAGE_LENGTH > 0) {
				$numpages++;
			}
			for($i=0; $i<$numpages; $i++){
				$pages[$i] = $i+1;
				if ($page==($i+1)) {
					$pages_current[$i] = " id=\"current\"";
				}else{
					$pages_current[$i] = "";
				}
			}
			$this->assign("page",$pages);
			$this->assign("current_page",$pages_current);
			
			foreach ($res as $row){
				$foxid = $this->getFoxID($row["komid"]);
				$url = "http://cvet.yellow/yap1/ugovori.fox.php?a=searchProfile&id=$foxid";
				$ugovor = @implode("",@file($url));
				if (strlen($ugovor)) {
					list($rank,$lastugo) = explode("{!}",$ugovor);
					$ugovori[$row["komid"]] = $rank;
					$ugovori_datumi[$row["komid"]] = $lastugo;
				}
				$data[$row["komid"]]["id"] = $row["komid"];
				$data[$row["komid"]]["name"] = $row["komname"];
				$data[$row["komid"]]["adresa"] = $row["komdel_adresa_id"];
				$data[$row["komid"]]["profil"] = $row["profil_text"];
			}
			natsort($ugovori);
			$ugovori = array_reverse($ugovori,true);
			
			//print_rarray($data);die();
			//print_rarray($ugovori);die();
			foreach ($ugovori as $komid=>$rank){
				$v = $data[$komid];
				//foreach ($data[$komid]["profil"] as $k=>$m){
				
				$komitent_name[] = $v["name"];
				$komitent_id[] = $komid;
				
				$adrid = $v["adresa"];
				$a = $this->adrese->getAll($adrid);
				$ul = $a["ulica"]." ".$a["broj"];
				$mesto = $a["lokacija"]["mesto"]["name"];
				if(isset($a["lokacija"]["opstina"])){
					$mesto .= "/".$a["lokacija"]["opstina"]["name"];
				}
				if (isset($a["lokacija"]["naselje"])) {
					$mesto .= "/".$a["lokacija"]["naselje"]["name"];
				}
				$ka = "<br />$mesto, $ul";
				$komitenti_adrese[] = $ka;
				
				$dels = $this->db->select2("SELECT komdel_del_id, delatnost_ime FROM komitenti_delatnosti kd, delatnosti d WHERE kd.komdel_del_id=delatnost_id AND komdel_kom_id=$komid GROUP BY komdel_del_id ORDER BY delatnost_ime");
				$deles = "";
				foreach ($dels as $row){
					$deles .= "<div style=\"font-size:11px;\" title=\"".$row["komdel_del_id"]."\">".$row["delatnost_ime"]."</div>";
				}
				$delatnosti[] = $deles;
				
				$offset = 20;
				$ptext = $v["profil"];
				$fpos = stripos($ptext,$kword);
				if($fpos < $offset){
					$ptext = substr($ptext,0,$fpos+strlen($kword)+$offset)."...";
				}else{
					$ptext = "...".substr($ptext,($fpos-$offset),strlen($kword)+(2*$offset))."...";
				}
				
				//$ptext .= "<br />".($fpos-$offset);
				$profiles[] = str_ireplace("$kword","<span style=\"text-decoration:underline; color:#ff8000;\">$kword</span>",$ptext);
				
				$ugorank[] = $rank>0?' class="ugovor"':"";
				
			}
			
			$prev = ""; $i=0;
			foreach ($komitent_id as $k=>$v){
				if($v == $prev){
					$komitent_id[$k] = "";
					$komitent_name[$k] = "";
				}else{
					$i++;
				}
				
				$prev = $v;
			}
			
			$this->assign("info","$ukupno komitenata");
			$this->assign("ugovor",$ugorank);
			$this->assign("komitent_id",$komitent_id);
			$this->assign("komitent_adrese",$komitenti_adrese);
			$this->assign("komitent_name",$komitent_name);
			$this->assign("delatnost",$delatnosti);
			$this->assign("profil",$profiles);
		}else{
			$this->assign("comment_start","<!--");
			$this->assign("comment_end","-->No results");
		}
		
		echo $this->parseTemplate("komitenti/adv_search_table_profile.tpl");
	}
	function advanceSearchBrand(){
		$kword = readValFromInput("kword");
		$q = "SELECT komitent_id, komitent_name, delatnost_ime, brand_name, b.brand_id "
			."FROM komitenti k, komitenti_delatnosti kd, delatnosti d, brands b, komitenti_brands kb "
			."WHERE k.komitent_id=kd.komdel_kom_id "
			."AND kd.komdel_del_id=d.delatnost_id "
			."AND k.komitent_id=kb.kom_id "
			."AND kd.komdel_del_id=kb.del_id "
			."AND kb.brand_id=b.brand_id "
			."AND b.brand_name LIKE '%".addslashes($kword)."%' "
			."GROUP BY komitent_id "
			."ORDER BY komitent_name";
		$res = $this->db->select2($q);
		if($res !== false){
			
			$this->assign("search_term","brand: <i>$kword</i>");
			
			foreach ($res as $row){
				$ids[] 	= $row["komitent_id"];
				$names[]= $row["komitent_name"];
				$dels[]	= $row["delatnost_ime"];
				
				$brand[]= $row["brand_name"];
				$brand_id[]= $row["brand_id"];
			}
			$this->assign("komitent_id",$ids);
			$this->assign("komitent_name",$names);
			$this->assign("delatnost",$dels);
			$this->assign("brand",$brand);
			$this->assign("brand_id",$brand_id);
		}else{
			$this->assign("comment_start","<!--");
			$this->assign("comment_end","-->Nema rezultata.");
		}
		
		echo $this->parseTemplate("komitenti/adv_search_table_brand.tpl");
	}
	function advanceSearchAttribute(){
		$kword = readValFromInput("keyword");
		$attrib = getFromInput("attrib");
		
		if (strlen($kword)) {
			switch ($attrib){
				case 1:				// telefon
					$kword = preg_replace('/[^\d]/',"",$kword);
					if (strlen($kword)<3) {
						die("Morate uneti minimum 3 cifre");
					}
					$search_key = "telefon";
					$q = "SELECT DISTINCT kom_id as komid, komitent_name as komname, telefon as searched "
						."FROM komitenti k, komitenti_telefoni kt "
						."WHERE k.komitent_id=kt.kom_id "
						."AND kt.fax=0 "
						."AND REPLACE(kt.telefon,' ','') LIKE '%$kword%' "
						."ORDER BY k.komitent_name";
					break;
				case 2:				// fax
					$kword = preg_replace('/[^\d]/',"",$kword);
					if (strlen($kword)<3) {
						die("Morate uneti minimum 3 cifre");
					}
					$q = "SELECT DISTINCT kom_id as komid, komitent_name as komname, telefon as searched "
						."FROM komitenti k, komitenti_telefoni kt "
						."WHERE k.komitent_id=kt.kom_id "
						."AND kt.fax=1 "
						."AND REPLACE(kt.telefon,' ','') LIKE '%$kword%' "
						."ORDER BY k.komitent_name";
					$search_key = "faks";
					break;
				case 3:				// web
					if (strlen($kword)<3) {
						die("Morate uneti minimum 3 karaktera");
					}
					$q = "SELECT DISTINCT kom_id as komid, komitent_name as komname, web as searched "
						."FROM komitenti k, komitenti_webs kw "
						."WHERE k.komitent_id=kw.kom_id "
						."AND web LIKE '%$kword%'"
						."ORDER BY k.komitent_name";
						$search_key = "web adresa";
					break;
				case 4:				// e-mail
					if (strlen($kword)<3) {
						die("Morate uneti minimum 3 karaktera");
					}
					$q = "SELECT DISTINCT kom_id as komid, komitent_name as komname, email as searched "
						."FROM komitenti k, komitenti_emails ke "
						."WHERE k.komitent_id=ke.kom_id "
						."AND email LIKE '%$kword%'"
						."ORDER BY k.komitent_name";
					$search_key = "e-mail adresa";
					break;
				case 5:				// ZR
					if (strlen($kword)<3) {
						die("Morate uneti minimum 3 karaktera.");
					}
					$q = "SELECT DISTINCT ziro_komitent_id as komid, komitent_name as komname, CONCAT(banka_name,', ',ziro_value) as searched "
						."FROM komitenti k, komitenti_ziro_racuni kzr, banke b "
						."WHERE k.komitent_id=ziro_komitent_id "
						."AND ziro_banka_id=banka_id "
						."AND ziro_value LIKE '%$kword%' "
						."ORDER BY k.komitent_name";
					$search_key = "žiro račun";
					break;
			}
			$this->assign("search_term","$attr: <i>$kword</i>");
			
			$res = $this->db->select2($q);
			if($res !== false){
				$this->assign("count",count($res));
				foreach ($res as $row){
					$komids[] = $row["komid"];
					$komnames[] = $row["komname"];
					
					$sval[] = $row["searched"];
				}
				$this->assign("searched_key",$search_key);
				$this->assign("searched_value",$sval);
				$this->assign("komid",$komids);
				$this->assign("komname",$komnames);
				echo $this->parseTemplate("komitenti/adv_search_table_attr.tpl");
			}else{
				echo "No results";
			}
		}else{
			echo "Unesite ključnu reč pretrage.";
		}
	}
	function advanceSearchDel($post){
		$delid = getFromInput("delatnost");
		
		$komname = trim(readValFromInput("filter_komitent"));
		
		$q = "SELECT komitent_id, komitent_name, komitent_name1, komdel_adresa_id "
			."FROM komitenti k, komitenti_delatnosti kd "
			."WHERE k.komitent_id=kd.komdel_kom_id "
			."AND kd.komdel_del_id=$delid ";
		
		if(isset($komname)){
			$q .= "AND (komitent_name LIKE '%$komname%' OR komitent_name1 LIKE '%$komname%') ";
			$this->assign("filter_komitent",$komname);
		}
			
		
		$q .= "ORDER BY komitent_name, komitent_name1";
		$res = $this->db->select2($q);
		
		if($res === false){
			$this->assign("comment_start","<!--");
			$this->assign("comment_end","-->No results.");
		}else{
			
			$st = "delatnost: <i>".$this->db->getOne("SELECT delatnost_ime FROM delatnosti WHERE delatnost_id=$delid LIMIT 1")."</i>";
			if (strlen($komname)) {
				$st .= ", komitent: <i>$komname</i>";
			}
			$this->assign("search_term",$st);
			$lista = array();
			foreach ($res as $key=>$row){
				$id = $row["komitent_id"];
				$name = $row["komitent_name"];
				$name1 = $row["komitent_name1"];
				$adresa = $row["komdel_adresa_id"];
				
				$lista[$id]["name"] = $name;
				$lista[$id]["name1"] = $name1;
								
				$lista[$id]["adresa"] = $adresa;
				
				$q = "SELECT telefon FROM komitenti_telefoni WHERE kom_id=$id AND del_id=$delid AND fax=0";
				$res_tel = $this->db->select2($q);
				if($res_tel !== false){
					foreach ($res_tel as $tel){
						$lista[$id]["telefoni"][] = $tel["telefon"];
					}
					$lista[$id]["telefoni"] = array_unique($lista[$id]["telefoni"]);
				}else{
					$lista[$id]["telefoni"] = array();
				}
			}
			//print_rarray($lista);die();
			//print_rarray($lista);
			$this->assign("info","Ukupno: ".count($lista));
			foreach ($lista as $komitent_id=>$row){
				$imapodatke=true;
				$ids[] = $komitent_id;
				$names[] = $row["name"];
				
				$adrobj = $this->adrese->getAll($row["adresa"]);
				//echo $komitent_id; print_rarray($adrobj);
				$ptt = $adrobj["lokacija"]["mesto"]["ptt"];
				$lok = $adrobj["lokacija"]["mesto"]["name"];
				
				if (isset($adrobj["lokacija"]["opstina"])){
					$lok .= " / ".$adrobj["lokacija"]["opstina"]["name"];
					$ptt = $adrobj["lokacija"]["opstina"]["ptt"];
				}
				
				if (isset($adrobj["lokacija"]["naselje"])) {
					$lok .= " / ".$adrobj["lokacija"]["naselje"]["name"];
					$ptt = $adrobj["lokacija"]["naselje"]["ptt"];
				}
				
				$mesta[] = "$ptt $lok";
				$adr_info[] = $adrobj["ulica"]." ".$adrobj["broj"];
				
				$telpod = "";
				foreach ($row["telefoni"] as $t){
					$telpod .= ", $t";
				}
				$telpod = substr($telpod,2);
				$tels[] = $telpod;
			}
			$this->assign("komitent_id",$ids);
			$this->assign("komitent_name",$names);
			$this->assign("komitent_name1",$names1);
			$this->assign("komitent_mesto",$mesta);
			$this->assign("komitent_adrese",$adr_info);
			$this->assign("komitent_telefoni",$tels);
		}
		
		echo $this->parseTemplate("komitenti/adv_search_table_del.tpl");
	}
	function advanceSearchDownload($q){
		$res = @$this->db->select2($q);
		
		if ($res !== false) {
			$out = "šifra\tnaziv\tadresa\n";
			$neparni = $parni = array();
			foreach ($res as $k=>$row){
				$line = $row["komid"]."\t".$row["komitent_name"]."\t".$row["ulica_ime"]." ".$row["adresa_broj"];
				
				preg_match('/[^\d]*(\d+)[^\d]*/',$row["adresa_broj"],$broj);
				$broj = intval($broj[1]);
				if ($broj%2 == 0) {
					$parni[] = $line;
				}else{
					$neparni[] = $line;
				}
				
			}
			?>
			<div class="area">
			<textarea style="width:800px; height:600px;""><?php echo implode("\r\n",$parni)."\r\n".implode("\r\n",$neparni); ?></textarea>
			</div>
			<?php
		}
	}
	function advanceSearchReportTM(){
		$query = readValFromInput("q");
		//echo $query;
		$this->assign("filter_query",$query);
		
		$start_date = date2int(getFromInput("start_date"));
		$end_date = date2int(getFromInput("end_date"));
		$submitted = getFromInput("sbt");
		
		if ($submitted>0) {
			if ($start_date>0 && $end_date>0 && ($end_date>=$start_date)) {
				
				$res = $this->db->select2($query." ORDER BY komitent_name");
				$komitenti_ids = array();
				foreach ($res as $row){
					$key = count($komitenti_ids);
					if (array_search($row["komid"],$komitenti_ids)===false) {
						$komitenti_ids[$key] = $row["komid"];
						$komitenti_names[$key] = $row["komitent_name"];
					}
				}
				$end_date = $end_date+(60*60*24);
				$non_called=0;
				$suma = array();
				foreach ($komitenti_ids as $k=>$komid){
					$komname = $komitenti_names[$k];
					$komname_url[$k] = urlencode($komitenti_names[$k]);
					$q = "SELECT *"
						."FROM rokovnik "
						."WHERE komitent_id=$komid "
						."AND time>$start_date AND time<$end_date "
						."ORDER BY time DESC";
					$res = $this->db->select2($q);
					$r_time = $r_response = $r_result = $r_radnik = "";
					if ($res !== false) {
						foreach ($res as $row){
							$r_time .= int2date($row["time"],"d.m.Y H:i")."<br />";
							$radnik = $this->db->getOne("SELECT CONCAT(radnici.radnik_ime,' ',radnici.radnik_prezime) FROM users,radnici WHERE users.radnik_id=radnici.radnik_id AND users.id=".$row["user_id"]." LIMIT 1");
							$suma["radnici"][$radnik][] = "1";
							$r_radnik .= "$radnik<br />";
							$odg = $this->db->getOne("SELECT name FROM rokovnik_odgovor WHERE id=".$row["odgovor"]." LIMIT 1");
							$suma["odgovor"][$odg][] = "1";
							$r_response .= "$odg<br />";
							$ish = $this->db->getOne("SELECT name FROM rokovnik r, rokovnik_result_type rrt, rokovnik_result rr WHERE r.id=rr.rokovnik_id AND rr.type=rrt.id AND r.id=".$row["id"]." LIMIT 1");
							$suma["ishod"][$ish][] = "1";
							$r_result .= "$ish<br />";
						}
					}else{
						$non_called++;
					}
					
					$q = "SELECT DISTINCT delatnost_ime "
						."FROM delatnosti, komitenti_delatnosti "
						."WHERE komdel_del_id=delatnost_id "
						."AND komdel_kom_id=$komid "
						."ORDER BY delatnost_ime";
					$delatnosti = $this->db->select1($q);
					$dels = "<ol>";
					foreach ($delatnosti as $del){
						$dels .= "<li>".$del[0]."</li>";
					}
					$dels .= "</ol>";
					$komitent_delatnosti[] = $dels;
					$rokovnik_radnik[] = $r_radnik;
					$rokovnik_time[] = $r_time;
					$rokovnik_response[] = $r_response;
					$rokovnik_result[] = $r_result;
				}
				
				$odgovori = "";
				if(count($suma["odgovor"])>0){
					foreach ($suma["odgovor"] as $k=>$v){
						if ($k=="") {
							$k = "bez odgovora";
						}
						$odgovori .= "<span class=\"label\">$k:</span><span class=\"value\">".count($v)."</span>";
					}
				}
				
				$ishodi = "";
				if(count($suma["ishod"])>0){
					foreach ($suma["ishod"] as $k=>$v){
						$ishodi .= "<span class=\"label\">$k:</span><span class=\"value\">".count($v)."</span>";
					}
				}
				
				$radnici = "";
				if(count($suma["radnici"])>0){
					ksort($suma["radnici"]);
					foreach ($suma["radnici"] as $k=>$v){
						$radnici .= "<span class=\"label\">$k:</span><span class=\"value\">".count($v)."</span>";
					}
				}
				
				$this->assign("radnici",$radnici);
				$this->assign("odgovori",$odgovori);
				$this->assign("ishodi",$ishodi);
				$this->assign("num",count($komitenti_ids));
				$this->assign("noncalled",$non_called);
				$this->assign("komid",$komitenti_ids);
				$this->assign("komdels",$komitent_delatnosti);
				$this->assign("komname",$komitenti_names);
				$this->assign("komname_url",$komname_url);
				$this->assign("rokovnik_time",$rokovnik_time);
				$this->assign("rokovnik_response",$rokovnik_response);
				$this->assign("rokovnik_result",$rokovnik_result);
				$this->assign("rokovnik_radnik",$rokovnik_radnik);
				echo $this->parseTemplate("komitenti/search_reportTM_table.tpl");
			}else{
				echo "Odaberite period pretrage.";
			}
		}else{
			$now = time();
			$this->assign("start_date",int2date($now-(60*60*24)));
			$this->assign("end_date",int2date($now));
			echo $this->parseTemplate("komitenti/search_reportTM.tpl");
		}
	}
	function searchKomiteniByAddress($addresses){
		$ret = null;
		$ids = array();
		//-----------------------
		//		komitenti
		//-----------------------
		$q = "SELECT DISTINCT komitent_id, komitent_name, komitent_adresa, komitent_direktor, komitent_direktor_tel "
			."FROM komitenti WHERE (";
		foreach ($addresses as $row){
			$q .= "komitent_adresa=".$row[0]." OR ";
		}
		$q = substr($q,0,strlen($q)-4).") ORDER BY komitent_name";
		$res = $this->db->select2($q);
		
		if($res[0]){
			foreach ($res as $k=>$komitent){
				if(array_search($komitent["komitent_id"],$ids) === false){
					$ids[$komitent["komitent_id"]] = $komitent["komitent_id"];
				}
			}
		}
		
		//-----------------------
		// komitenti_delatnosti
		//-----------------------
		$q = "SELECT DISTINCT k.komitent_id, k.komitent_name, k.komitent_direktor, k.komitent_direktor_tel, kd.komdel_adresa_id as komitent_adresa "
			."FROM komitenti k, komitenti_delatnosti kd "
			."WHERE k.komitent_id=kd.komdel_kom_id AND (";
		foreach ($addresses as $row){
			$q .= "komdel_adresa_id=".$row[0]." OR ";
		}
		$q = substr($q,0,strlen($q)-4).") ORDER BY komitent_name";
		$res_del = $this->db->select2($q);
		if($res_del[0]){
			foreach ($res_del as $k=>$del){
				$search = array_search($del["komitent_id"],$ids);
				if($search !== false){
					unset($res_del[$k]);
				}
			}
			if($res[0]){
				$all_res = array_merge($res,$res_del);
			}else{
				$all_res = $res_del;
			}
		}else{
			$all_res = $res;
		}
		$ret = $all_res;
		return $ret;
	}
	
	function getUgovori(){
		// iz MySQL-a
		echo $this->get_KomitentUgovoriList(getFromInput("id"));
		
		// IZ FOX-a
		/*$remote_uri = "http://cvet.yellow/yap1/komitenti.php";
		$uri = $_SERVER['REQUEST_URI'];
		$params = substr($uri,strpos($uri,"?"));
		file_put_contents("tmpVOJA",$remote_uri.$params);
		echo implode("",file($remote_uri.$params));*/
	}
	
	//----------------------------------------------------------------------------
	//************************			LISTING			**************************
	//----------------------------------------------------------------------------
		
	function listingDelatnosti(){
		$error=false;
		
		$delatnost = ($delid===null)?getFromInput("delatnost"):$delid;
		$kampanja  = ($kamid===null)?getFromInput("kampanja"):$kamid;
		
		if($kampanja){
			$settings = $this->getSettings($kampanja);
			
			if($settings === false || !isset($settings["opstine"]) || !isset($settings["delimiter"])){
				$error=true;
				$msg="Nema definisanih podešavanja za odabranu kampanju.";
			}
		}else{
			$error=true;
			$msg="Pokrenite generisanje listinga.";
		}
		if($error){
			$this->assign("comment_start","<!--");
			$this->assign("comment_end","-->$msg");
		}
		
		$this->assign("delatnost_id",$delatnost);
		$polja = $this->get_Delatnosti($delatnost);
			$this->assign("del_id",$polja["id"]);
			$this->assign("del_name",$polja["name"]);
			$this->assign("selected_del",$polja["selected"]);
		$polja = $this->get_Kampanje($kampanja);
			$this->assign("kampanja_id",$polja["id"]);
			$this->assign("kampanja_name",$polja["name"]);
			$this->assign("selected_kampanja",$polja["selected"]);
		
		if(!$error){
			
			$listing = array();
			
			$this->assign("delimiter",$settings["delimiter"]);
			//file_put_contents("voja",var_export($this->_arej,true));
			
			$opstine = explode(";",$settings["opstine"]);
			$tmp = array();
			foreach ($opstine as $k=>$opstina_id){
				$opstine[$k]["mesta"] = array();
				$gradovi = $this->db->select1("SELECT lid FROM lokacije WHERE lok_tip=1 AND lok_parent=$opstina_id");
				if($gradovi){
					foreach ($gradovi as $row){
						$tmp[$k]["mesta"][] = $row[0];
						
						$lo = $this->db->select1("SELECT lid FROM lokacije WHERE lok_tip=2 AND lok_parent=".$row[0]);
						if($lo){
							foreach ($lo as $loid){
								$tmp[$k]["lokopstine"][]=$loid[0];
							}
						}
					}
				}
				
				$tmp[$k]["opsid"] = $opstina_id;
			}
			$opstine = $tmp;
			
			$query_grad = "(lokacije.lok_tip=1 AND (0 OR ";
			$query_lops = "(lokacije.lok_tip=2 AND (0 OR ";
			$query_nase = "(lokacije.lok_tip=3 AND (0 OR ";
			
			foreach ($opstine as $opstina){
				$query_grad .= "lok_parent=".$opstina["opsid"]." OR ";
				
				if(count($opstina["mesta"])){
					foreach ($opstina["mesta"] as $mesid){
						$query_lops .= "lok_parent=$mesid OR ";
					}
				}
				if(count($opstina["lokopstine"])){
					foreach ($opstina["lokopstine"] as $lid){
						$query_nase .= "lok_parent=$lid OR ";
					}
				}
			}
			$query_grad = substr($query_grad,0,strlen($query_grad)-4)."))";
			$query_lops = substr($query_lops,0,strlen($query_lops)-4)."))";
			$query_nase = substr($query_nase,0,strlen($query_nase)-4)."))";
			
			//die($query_grad."<br /><br />".$query_lops."<br /><br />".$query_nase);
			
			// DELATNOSTI
			$q = "SELECT komitent_id,komdel_del_id, komitent_name, komdel_adresa_id "
				."FROM komitenti, komitenti_delatnosti, adrese, lokacije "
				."WHERE komdel_adresa_id=adresa_id "
				."AND komitenti.komitent_view_status<3 "
				."AND komdel_kom_id=komitent_id "
				."AND adrese.adresa_lid=lokacije.lid ";
				
			$q .= "AND ($query_grad OR $query_lops OR $query_nase)";
			
			/*$q .= "AND ("
				."lokacije.lok_tip=1 "
				."AND (";
				foreach ($opstine as $opsid){
					$q .= "lok_parent=$opsid OR ";
				}
				$q = substr($q,0,strlen($q)-4).")";*/
			
			//$q_sve = preg_replace('/SELECT.*?FROM/i',"SELECT count(*) FROM",$q);
			//$sve = $this->db->getOne($q_sve);
			//$this->assign("ukupno_kampanja",$sve);
			//echo $q_sve;
			
			$q .= "AND komdel_del_id=$delatnost ";
			$q .= "ORDER BY komitent_name";
			
			//echo "$query_grad<br />$query_lops";
			
			
			// SRODNE DELATNOSTI
			$srodneDelatnosti = $this->get_DelatnostiFamilies($delatnost);
			if ($srodneDelatnosti) {
				foreach ($srodneDelatnosti["polje_ime"] as $ksd=>$vsd){
					$sd_name[$ksd] = $vsd;
					$sd_id[$ksd] = $srodneDelatnosti["polje_id"][$ksd];
				}
				$this->assign("sd_name",$sd_name);
				$this->assign("sd_id",$sd_id);
				$this->assign("srodne_delatnosti",implode("{!}",$sd_name));
			}else{
				$this->assign("comment_start_no_sd","<!--");
				$this->assign("comment_end_no_sd","--> Nema.");
			}
			
			// LINKOVI
			$sql = "SELECT u.komitent, us.delatnost "
				."FROM ugovori u, ugovori_stavke us, ugovori_tok_realizacije utr, knjiga_data kd "
				."WHERE u.id=us.ugovor_id "
				."AND us.stavka_id=utr.stavka "
				."AND utr.tok_id=kd.id_tok "
				."AND us.`kampanja`=$kampanja "
				."AND kd.`links` LIKE '%;$delatnost;%'";
			$res = $this->db->select2($sql);
			if ($res) {
				foreach ($res as $kl=>$vl){
					
					$sql = "SELECT komdel_adresa_id FROM komitenti_delatnosti "
						  ."WHERE komdel_kom_id=".$vl["komitent"]." "
						  ."AND komdel_del_id=".$vl["delatnost"]." "
						  ."LIMIT 1";
					$adrid = $this->db->getOne($sql);
					
					$sql = "SELECT telefon FROM komitenti_telefoni "
						  ."WHERE kom_id=".$vl["komitent"]." "
						  ."AND del_id=".$vl["delatnost"]." "
						  ."AND adresa=$adrid "
						  ."AND fax=0 "
						  ."ORDER BY `order` "
						  ."LIMIT 1";
					$tel = $this->db->getOne($sql);
						  
					$adr= $this->adrese->getAll($adrid);
					$links_adr[$kl] = $adr["ulica"]." ".$adr["broj"];
					$links_name[$kl] = $this->db->getOne("SELECT komitent_name FROM komitenti WHERE komitent_id=".$vl["komitent"]." LIMIT 1");
					$links_tels[$kl] = $tel;
				}
				$this->assign("l_adresa",$links_adr);
				$this->assign("l_name",$links_name);
				$this->assign("l_tel",$links_tels);
				$this->assign("links_names",implode("{!}",$links_name));
				$this->assign("links_adrese",implode("{!}",$links_adr));
				$this->assign("links_tels",implode("{!}",$links_tels));
			}else{
				$this->assign("comment_start_no_link","<!--");
				$this->assign("comment_end_no_link","--> Nema.");
			}
			$linkovi = $kampanja;
			
			$komdel = $this->db->select2($q);
			if($komdel !== false){
				foreach ($komdel as $row){
					foreach ($row as $k=>$v){
						$$k = $v;
					}
					
					$q = "SELECT DISTINCT telefon FROM komitenti_telefoni WHERE kom_id=$komitent_id AND del_id=$delatnost AND adresa=$komdel_adresa_id AND fax=0 ORDER BY `order`,telefon";
					$tels = $this->db->select2($q);
					if($tels){
						$telefon = $tels[0]["telefon"];
					}else{
						$telefon = "";
					}
					
					$listing[$komitent_id][$komdel_adresa_id]["name"] = $row["komitent_name"];
					if(!isset($listing[$komitent_id][$komdel_adresa_id]["telefoni"])){
						$listing[$komitent_id][$komdel_adresa_id]["telefoni"][] = $telefon;
					}
				}
			}
		}
		if(count($listing)){
			//print_rarray($listing);
			$num_komitenti = count($listing);
			foreach ($listing as $komid=>$v){
				foreach ($v as $adrid=>$m){
					$name = $m["name"];
					$adr = $this->adrese->getAll($adrid);
					
					$mesto = $adr["lokacija"]["mesto"]["name"];
					$mesto1 = null;
					
					//file_put_contents("tmpVOJA",var_export($adr,true));
					
					if(count($adr["lokacija"]["naselje"])){
						$mesto1 = $adr["lokacija"]["naselje"]["name"];
						//$mesto = $adr["lokacija"]["mesto"]["name"]." / ".$adr["lokacija"]["opstina"]["name"]." / ".$adr["lokacija"]["naselje"]["name"];
					}else if(count($adr["lokacija"]["opstina"])){
						$mesto1 = $adr["lokacija"]["opstina"]["name"];
						//$mesto = $adr["lokacija"]["mesto"]["name"]." / ".$adr["lokacija"]["opstina"]["name"];
					}
					
					if ($mesto1!==null && in_array($adr["lokacija"]["mesto"]["id"],array_keys($this->mesta_skracenice))) {
						$mesto = $this->mesta_skracenice[$adr["lokacija"]["mesto"]["id"]].", $mesto1";
					}
					
					$ulica = $adr["ulica"];
					if(preg_match('/^bulevar/i',$ulica)){
						$ulica = str_ireplace("bulevar","Bul.",$ulica);
					}
					$adresa = "$ulica ".$adr["broj"];
					$tel = $m["telefoni"][0];
					
					$ids[] = $komid;
					$names[] = $name;
					$mesta[] = $mesto;
					$adres[] = $adresa;
					$telef[] = $tel;
					
					//echo "$komid - $name - $mesto - [$adrid]$adresa - $tel<br />";
					
					/*$q = "SELECT telefon FROM komitenti_telefoni WHERE kom_id=$komid AND del_id=0 AND fax=0 AND (telefon!='";
					$q .= implode("' AND telefon!='",$m["telefoni"])."') ORDER BY telefon";
					$add_tel = $this->db->select2($q);
					if($add_tel !== false){
						foreach ($add_tel as $at){
							$m["telefoni"][] = $at["telefon"];
						}
					}
					foreach ($m["telefoni"] as $tel){
						$ids[] = $komid;
						$names[] = $name;
						$mesta[] = $mesto;
						$adres[] = $adresa;
						$telef[] = $tel;
						$i++;
					}*/
				}
			}
			$num_zapisa = count($ids);
			
			$this->assign("info","$num_komitenti komitenata / $num_zapisa zapisa");
			
			$theDelatnost = $this->db->getOne("SELECT delatnost_ime FROM delatnosti WHERE delatnost_id=$delatnost");
			$this->assign("the_delatnost",$theDelatnost);
			$this->assign("komitent_id",$ids);
			$this->assign("ime",$names);
			$this->assign("mesto",$mesta);
			$this->assign("adresa",$adres);
			$this->assign("telefon",$telef);
		}
		
		echo $this->parseTemplate("komitenti/listing_delatnosti.tpl");
	}
	function listingDelatnostiUkupno(){
		$kamid = getFromInput("kamid");
		
		$sett = $this->getSettings($kamid);
		if ($sett !== false && isset($sett["opstine"])) {
			$opstine = explode(";",$sett["opstine"]);
			$lids = array();
			
			foreach ($opstine as $opsid){
				$grad = $this->db->select1("SELECT lid FROM lokacije WHERE lok_tip=1 AND lok_parent=$opsid");
				if ($grad !== false) {
					foreach ($grad as $gradid){
						$lids[] = $gradid[0];
						$lopstina = $this->db->select1("SELECT lid FROM lokacije WHERE lok_tip=2 AND lok_parent=".$gradid[0]);
						if ($lopstina !== false) {
							foreach ($lopstina as $lopsid){
								$lids[] = $lopsid[0];
								$naselje = $this->db->select1("SELECT lid FROM lokacije WHERE lok_tip=3 AND lok_parent=".$lopsid[0]);
								if ($naselje !== false) {
									foreach ($naselje as $nasid){
										$lids[] = $nasid[0];
									}
								}
							}
						}
					}
				}
			}
			if (count($lids)) {
				$lids = array_unique($lids);
				
				$q = "SELECT DISTINCT CONCAT(komdel_kom_id, komdel_del_id, komdel_adresa_id) "
					."FROM komitenti_delatnosti kd, adrese a "
					."WHERE kd.komdel_adresa_id=a.adresa_id "
					."AND (0";
				foreach ($lids as $lid){
					$q .= " OR a.adresa_lid=$lid";
				}
				$q .= ")";
				$res = $this->db->select1($q);
				$msg = "Ukupno za sve delatnosti ".count($res);
			}else{
				$msg = "Nema adresa u definisanim opštinama.";
			}
		}else{
			$msg = "Nema definisanih opština u podešavanjima listinga.";
		}
		
		echo "<div class=\"area\"><h1>$msg</h1></div>";
	
	}
	function listingSettings(){
		$kampanja = getFromInput("kampanja");
		
		$func = getFromInput("func");
		if($func == "setContent"){
			$this->assign("comment_start_advance","");
			$this->assign("comment_end_advance","");
		}else{
			$input = '<input type="hidden" name="skipDelim" value="1" />';
			$this->assign("comment_start_advance","<!--");
			$this->assign("comment_end_advance","-->$input");
		}
		
		
		$polja = $this->get_Kampanje($kampanja);
			$this->assign("kampanja_id",$polja["id"]);
			$this->assign("kampanja_name",$polja["name"]);
			$this->assign("selected_kampanja",$polja["selected"]);
		if(!$kampanja){
			$kampanja = $polja["id"][0];
		}
			
			
		$polja = $this->get_Opstine();
			$this->assign("opsid",$polja["polje_id"]);
			$this->assign("opsname",$polja["polje_ime"]);
		$this->assign("kamid",$kampanja);
		
		
		$settings = $this->getSettings($kampanja);
		if($settings !== false){
			if(isset($settings["opstine"])){
				$i=1;
				$ops = $this->get_Opstine();
				$opstine = explode(";",$settings["opstine"]);
				foreach ($opstine as $opsid){
					$opts = "";
					foreach ($ops["polje_id"] as $k=>$id){
						
						$opts .= '<option value="'.$id.'"';
						if($id == $opsid){
							$opts .= " selected";
						}
						
						$opts .= '>'.$ops["polje_ime"][$k].'</option>'."\n";
					}
					$items[] = $i;
					$options[] = $opts;
					
					$i++;
				}
				$this->assign("item",$items);
				$this->assign("opstina_options",$options);
			}else{
				$this->assign("comment_start","<!--");
				$this->assign("comment_end","-->");
			}
			
			if(isset($settings["delimiter"])){
				$delims = explode(";",$settings["delimiter"],3);
				$this->assign("delim1",$delims[0]);
				$this->assign("delim2",$delims[1]);
				$this->assign("delim3",$delims[2]);
			}
		}
		
		$this->assign("func",$func);
		echo $this->parseTemplate("komitenti/listing_delatnosti_settings.tpl");
	}
	function listingSettingsSave(){
		$input = $_POST;
		$err = false;
		
		foreach ($input as $name=>$value){
			if(preg_match('/^opstina_/',$name)){
				$opstine[] = $value;
			}else{
				$$name = trim($value);
			}
		}
		
		$time = time();
		$user = $_COOKIE["ypu"];
		$ip = $_SERVER['REMOTE_ADDR'];
		
		if(is_array($opstine)){
			$value = implode(";",$opstine);
		}else{
			$value = false;
		}
		
		// OPSTINE
		$q = "SELECT * FROM listing_settings WHERE kampanja=$kampanja_id AND name='opstine'";
		$res = $this->db->select2($q);
		
		if($value === false){
			$q = "DELETE FROM listing_settings WHERE kampanja=$kampanja_id AND name='opstine'";
		}elseif($res !== false){
			$q = "UPDATE listing_settings SET "
				."value='$value', "
				."time=$time, "
				."user=$user, "
				."ip='$ip' "
				."WHERE name='opstine' AND kampanja=$kampanja_id";
		}else{
			$q = "INSERT INTO listing_settings VALUES('opstine',$kampanja_id,'$value',$user,$time,'$ip')";
		}
		if($this->db->alterTable($q)){
			$err=true;
		}
		
		// DELIMITER
		if(!isset($skipDelim)){
			$q = "SELECT 1 FROM listing_settings WHERE kampanja=$kampanja_id AND name='delimiter'";
			$res = $this->db->select2($q);
			if(!strlen($delim1) && !strlen($delim2) && !strlen($delim3)){
				$q = "DELETE FROM listing_settings WHERE kampanja=$kampanja_id AND name='delimiter'";
			}else if ($res!==false) {
				$q = "UPDATE listing_settings SET "
					."value='$delim1;$delim2;$delim3;', "
					."time=$time, "
					."user=$user, "
					."ip='$ip' "
					."WHERE name='delimiter' AND kampanja=$kampanja_id";
			}else{
				$q = "INSERT INTO listing_settings VALUES('delimiter',$kampanja_id,'$delim1;$delim2;$delim3',$user,$time,'$ip')";
			}
			if(!$this->db->alterTable($q)){
				$err=true;
			}
		}
		
		if($err === false){
			echo "Podešavanja su sačuvana.";
		}else{
			echo mysql_error();
		}
		
	}
	function listingMakeTXT(){
		
		$delid = getFromInput("delid");
		$delname = $this->db->getOne("SELECT delatnost_ime FROM delatnosti WHERE delatnost_id=$delid LIMIT 1");
		$delname = strtotitle($delname);
		
		$data = readValFromInput("data");
		$data = stripslashes($data);
		//$data = utf2yuscii($data);
		
		$data = html_entity_decode($data);
		
		$delim = getFromInput("delim");
		$delim = explode(";",$delim);
		$delim1 = $delim[0];
		$delim2 = $delim[1];
		$delim3 = $delim[2];
		
		// srodne delatnosti
		$srodne_delatnosti = readValFromInput("srodne_delatnosti",true);
		if (strlen($srodne_delatnosti)>0) {
			$srodne_delatnosti = explode("{!}",$srodne_delatnosti);
		}else{
			$srodne_delatnosti = array();
		}
		
		// linkovi
		$links_names = explode("{!}",readValFromInput("links_names"));
		$links_adrese = explode("{!}",readValFromInput("links_adrese"));
		$links_tels = explode("{!}",readValFromInput("links_tels"));
		foreach ($links_names as $k=>$v){
			if (strlen(trim($v))>0) {
				$links[$k]["name"] = $v;
				$links[$k]["address"] = $links_adrese[$k];
				$links[$k]["phone"] = $links_tels[$k];
			}
		}
		
		
		$tmp = preg_split('/(.*?=.*?)(\{!+\})+/',$data,-1,PREG_SPLIT_DELIM_CAPTURE);
		foreach ($tmp as $k=>$line){
			if(strlen($line)<1 || preg_match('/^\{!+\}$/',$line)){
				unset($tmp[$k]);
			}
		}
		//file_put_contents("voja",var_export($tmp,true));
		$data = array();
		foreach ($tmp as $k=>$l){
			$tt = explode("=",$l,2);
			$i = count($data);
			if($tt[0]=="name"){
				$i++;
			}
			$data[$i][$tt[0]] = $tt[1];
		}
		
		$out = "";
		$txt_out_list = "";
		
		foreach ($data as $d){
			$out .= $this->listingTXTRowDelimiter.$d['name'].$delim1.$d['mesto'].$delim2.$d['adresa'].$delim3.$d['telefon'];
			$txt_out_list .= "\n"
						.$this->listingStyleDelimiter."s6".$this->listingStyleDelimiter.$d['name']." - ".$d['mesto'].$delim2
						.$d['adresa'].$delim3.$d['telefon'];
		}
		$out = substr($out,strlen($this->listingTXTRowDelimiter));
		/*
		$data = array();
		foreach ($tmp as $line){
			if(strlen($line) && !preg_match('/^{!+}$/',$line)){
				$t = explode("=",$line,2);
				$varname = trim($t[0]);
				$varval  = trim($t[1]);
				
				$data[$varname][] = $varval;
			}
		}
		$out = "";
		$keys = array_keys($data);
		foreach ($data[$keys[0]] as $k=>$v){
			if(1){
			//if(strlen(trim($data[$keys[2]][$k]))){
				$out .= "\r\n$v$delim1".$data[$keys[1]][$k]."$delim2".$data[$keys[2]][$k]."$delim3".$data[$keys[3]][$k];
			}
		}
		$out = substr($out,2);*/
		$tmpfilename = "tmp".$_COOKIE["ypu"];
		
		$txt_out = "";
		if (count($srodne_delatnosti)>0) {
			foreach ($srodne_delatnosti as $sd){
				$txt_out .= $this->listingStyleDelimiter."s1".$this->listingStyleDelimiter.$sd."\n";
			}
			$txt_out .= "\n";
		}
		$txt_out = preg_replace('/\n+$/',"\n",$txt_out);
		if (count($links)>0) {
			foreach ($links as $link){
				$txt_out .= $this->listingStyleDelimiter."s2".$this->listingStyleDelimiter.$link["name"]."\n";
				$txt_out .= $this->listingStyleDelimiter."s3".$this->listingStyleDelimiter.$link["address"];
				$txt_out .= "\t".$link["phone"]."\n";
				$txt_out .= $this->listingStyleDelimiter."s4".$this->listingStyleDelimiter."(vidi oglas na strani )\n";
			}
			$txt_out .= "\n";
		}
		$txt_out = preg_replace('/\n+$/',"\n",$txt_out);
		
		$txt_out_list = $this->listingStyleDelimiter."s5".$this->listingStyleDelimiter."$delname"
						.$txt_out_list;
		$txt_out .= trim($txt_out_list);
		
		file_put_contents($tmpfilename,$out);
		echo $this->testExportListingTXT($tmpfilename,$delim);
		file_put_contents($tmpfilename,$txt_out);
		
		echo "{!}$tmpfilename";
	}
	
	function testExportListingTXT($file,$delimiters){
		$file = implode("",file($file));
		
		$specials = array("^","$","{","}","(",")","/");
		foreach ($delimiters as $k=>$v){
			foreach ($specials as $spec){
				$delimiters[$k] = preg_replace('/\\'.$spec.'/e',"\\".$delimiters[$k],$delimiters[$k]);
			}
		}
		
		$rgx = '/(.*?)'.$delimiters[0].'(.*?)'.$delimiters[1].'(.*?)'.$delimiters[2].'(.*?)/';
		
		$tmp = explode($this->listingTXTRowDelimiter,$file);
		$this->assign("ukupno",count($tmp));
		foreach ($tmp as $k=>$row){
			$t = explode($delimiters[0],$row);
			$komitenti[$k] = utf2yuscii($t[0],true);
			
			$t = explode($delimiters[1],$t[1]);
			$mesta[$k] = utf2yuscii($t[0],true);
			
			$t = explode($delimiters[2],$t[1]);
			$adrese[$k] = utf2yuscii($t[0],true);
			
			$telefoni[$k] = utf2yuscii($t[1],true);
		}
		$this->assign("komitent",$komitenti);
		$this->assign("mesto",$mesta);
		$this->assign("adresa",$adrese);
		$this->assign("telefon",$telefoni);
		return $this->parseTemplate("komitenti/testListingTXTTable.tpl");
	}
	
	function listingBind(){
		
		$numFiles = getFromInput("num");
		$filename = str_replace(" ","_",readValFromInput("filename"));
		$kampanja = getFromInput("kampanja");
		if($numFiles > 0){
			
			// FETCH DELIMITERS
			$q = "SELECT value FROM listing_settings WHERE name='delimiter' AND kampanja=$kampanja";
			$delimiters = $this->db->getOne($q);
			if($delimiters === null){
				die("Za odabranu kampanju nisu podešeni delioci polja za listing.");
			}
			$delimiters = str_replace("\\n","\n",$delimiters);
			$delimiters = str_replace("\\t","\t",$delimiters);
			$delimiters = str_replace("\\s"," ",$delimiters);
			$delimiters = explode(";",$delimiters);
			
			
			for($i=1; $i<=$numFiles; $i++){
				$name		= $_FILES["file$i"]["name"];
				$tmp_name	= $_FILES["file$i"]["tmp_name"];
				$data[$name] = implode("",file($tmp_name));
			}
			
			foreach ($data as $k=>$filecontent){
				$filecontent = utf2yuscii($filecontent,true);
				$file = explode("%#%",$filecontent);
				/*foreach ($file as $k=>$v){
					if($k%2==1){
						$file[$k-1] .= $v;
						unset($file[$k]);
					}
				}
				$file = array_values($file);
				foreach ($file as $k=>$v){
					if($k%2==1){
						$file[$k-1] .= "\n".$v;
						unset($file[$k]);
					}
				}
				$file = array_values($file);*/
				
				
				$tmpTableName = "listingTemp";
				$params = array(
					"ime" => "varchar(100)",
					"mes" => "varchar(100)",
					"adr" => "varchar(200)",
					"tel" => "varchar(50)"
				
				);
				$sortkey = "ime ASC";
				
				if($this->db->createTempTable($tmpTableName,$params)){
					$q = array();
					foreach ($file as $v){
						$tmp = preg_split('/&%|\n|\t/',addslashes($v));
						$q = "INSERT INTO $tmpTableName VALUES('".$tmp[0]."','".$tmp[1]."','".$tmp[2]."','".$tmp[3]."')";
						if(!$this->db->alterTable($q)){
							die("Error!\r\n$q");
						}
						
					}
				}else{
					die("Error!");
				}
			}
			
			$res = $this->db->select2("SELECT * FROM $tmpTableName ORDER BY $sortkey");
			if($res !== false){
				header("Content-Type: text/txt");
				header("Content-Disposition: attachment; filename=$filename.txt");
				foreach ($res as $k=>$row){
					foreach ($row as $m=>$n){
						$row[$m] = utf2yuscii(stripslashes($n));
					}
					
					echo $row["ime"].$delimiters[0].$row["mes"].$delimiters[1].$row["adr"].$delimiters[2].$row["tel"];
					if($k < (count($res)-1)){
						echo "%#%";
					}
				}
			}
			$this->db->alterTable("DROP TABLE $tmpTableName");
			
		}else{
			$polja = $this->get_Kampanje();
				$this->assign("kampanja_id",$polja["id"]);
				$this->assign("kampanja_name",$polja["name"]);
			echo $this->parseTemplate("komitenti/listing_bind.tpl");
		}
	}
	
	//----------------------------------------------------------------------------
	//************************	LISTING BUSINESS	******************************
	//----------------------------------------------------------------------------
	
	function listingBusiness(){
		$db = $this->db;
		$addr = $this->adrese;
		$slova = array("#","a","b","c","č","ć","d","dž","đ","e","f","g","h","i","j","k","l","lj","m","n","nj","o","p","q","r","s","š","t","u","v","w","x","y","z","ž");
		$mesta_skracenice = array(
			45 => "Bg",		// Beograd
			199=> "N.Bg"	// Novi Beograd
		);
		// get from input
		$letter = readValFromInput("slovo");
		$kampanja = getFromInput("kampanja");
		$suma = getFromInput("suma"); $suma = strlen($suma)>0?true:false;
		//$oglasi = loadOglasi();
		//$indexFirmi = loadIndex();
		$download = getFromInput("download"); $download = $download>0?true:false;
		
		$this->assign("slovo_link",urlencode($letter));
		
		if ($download) {
			$file = file_get_contents("business.txt");
			header("Content-Type: text/txt; charset=utf-8;");
			header("Content-Disposition: attachment; filename=".$letter.".txt;");
			echo $file;
			die();
		}
		
		// filter slova
		foreach ($slova as $k=>$slovo){
			$sl[$k] = $slovo;
			$sls[$k] = $slovo==$letter?" selected":"";
		}
		$this->assign("slovo",$sl);
		$this->assign("slovo_selected",$sls);
		
		// filter kampanje
		$polja = $this->get_Kampanje($kampanja);
			$this->assign("kampanja_id",$polja["id"]);
			$this->assign("kampanja_name",$polja["name"]);
			$this->assign("kampanja_selected",$polja["selected"]);
			
		
		if (strlen($letter) && $kampanja>0) {
			// empty business pages listing table
			$db->alterTable("TRUNCATE TABLE listing_business");
			
			// GET OPSTINE
			$opstine = $db->getOne("SELECT value FROM listing_settings WHERE name='opstine' AND kampanja=$kampanja LIMIT 1");
			if (!$opstine) {
				$error = 1;
				$msg = "Nema definisanih podešavanja za odabranu kampanju.";
			}
			
			if ($error) {
				$this->assign("comment_start","<!--");
				$this->assign("comment_end","-->$msg");
			}else{
				$opstine = explode(";",$opstine);
				$lids = array();
				
				// GET DELIMITERS
				$q = "SELECT value FROM listing_settings WHERE name='delimiter' AND kampanja=$kampanja LIMIT 1";
				
				$delimiters = explode(";",$db->getOne($q));
				
				foreach ($opstine as $opsid){
					//echo "SELECT lid FROM lokacije WHERE lok_tip=1 AND lok_parent=$opsid<br />";
					$res1 = $db->select1("SELECT lid FROM lokacije WHERE lok_tip=1 AND lok_parent=$opsid");
					if ($res1 !== false) {
						foreach ($res1 as $row1){
							$lids[count($lids)] = $row1[0];
							$res2 = $db->select1("SELECT lid FROM lokacije WHERE lok_tip=2 AND lok_parent=".$row1[0]);
							if ($res2 !== false) {
								foreach ($res2 as $row2){
									$lids[count($lids)] = $row2[0];
									$res3 = $db->select1("SELECT lid FROM lokacije WHERE lok_tip=3 AND lok_parent=".$row2[0]);
									if ($res3 !== false) {
										foreach ($res3 as $row3){
											$lids[count($lids)] = $row3[0];
										}
									}
								}
							}
						}
					}
				}
				
				$bl = array();
				// KOMITENTI DELATNOSTI
				$q = "SELECT DISTINCT komitent_id, komitent_name, komdel_adresa_id "
					."FROM komitenti_delatnosti, komitenti, adrese "
					."WHERE komitent_id=komdel_kom_id "
					."AND komitent_view_status<3 "
					."AND komdel_adresa_id=adresa_id ";
				
				if (!$suma) {
					if ($letter!="n" && $letter!="d" && $letter!="#" && $letter!="l") {
						$q .= "AND komitent_name RLIKE '^$letter'";
					}else{
						switch ($letter){
							case "l":
							case "n":
								$q .= " AND komitent_name RLIKE '^$letter' AND komitent_name NOT RLIKE '^".$letter."j'";
								break;
							case "d":
								$q .= " AND komitent_name RLIKE '^d' AND komitent_name NOT RLIKE '^dž'";
								break;
							case "#":
								$q .= " AND komitent_name RLIKE '^[^a-zA-Zčćšđž]'";
								break;
						}
					}
				}
				
				$q .= " AND (0";
				foreach ($lids as $lid){
					$q .= " OR adresa_lid=$lid";
				}
				$q .= ") ORDER BY komitent_name";
				$adrese = $db->select1($q);
				
				if ($adrese!== false) {
					foreach ($adrese as $adr){
						$bl[$adr[0]]["komitent_id"] = $adr[0];
						$bl[$adr[0]]["komitent_name"] = $adr[1];
						$bl[$adr[0]]["adrese"][] = $adr[2];
						/*if (isset($bl[$adr[0]]["adrese"]) && !in_array($adr[2],$bl[$adr[0]]["adrese"])) {
							$bl[$adr[0]]["adrese"][] = $adr[2];
						}*/
					}
				}
				if ($suma) {
					echo count($adrese);
				}else{
					if (count($bl)>0) {
						foreach ($bl as $row){
							foreach ($row["adrese"] as $adr){
								$a = $addr->getAll($adr);
								$mesto = $a["lokacija"]["mesto"]["name"];
								$mesto1 = null;
								
								if(count($a["lokacija"]["naselje"])){
									$mesto1 = $a["lokacija"]["naselje"]["name"];
									//$mesto = $adr["lokacija"]["mesto"]["name"]." / ".$adr["lokacija"]["opstina"]["name"]." / ".$adr["lokacija"]["naselje"]["name"];
								}else if(count($a["lokacija"]["opstina"])){
									$mesto1 = $a["lokacija"]["opstina"]["name"];
									//$mesto = $adr["lokacija"]["mesto"]["name"]." / ".$adr["lokacija"]["opstina"]["name"];
								}
								
								if ($mesto1!==null && in_array($a["lokacija"]["mesto"]["id"],array_keys($mesta_skracenice))) {
									$mesto = $mesta_skracenice[$a["lokacija"]["mesto"]["id"]].", $mesto1";
								}
								$ulica = $a["ulica"];
								if(preg_match('/^bulevar/i',$ulica)){
									$ulica = str_ireplace("bulevar","Bul.",$ulica);
								}
								$adresa = "$ulica ".$a["broj"];
								$tel = $db->getOne("SELECT telefon FROM komitenti_telefoni WHERE telefon!='' AND fax=0 AND del_id>0 AND kom_id=".$row["komitent_id"]." AND adresa=$adr ORDER BY `order`, `telefon` LIMIT 1");
								
								
								$komitent_name = prepForSQL($row["komitent_name"]);
								//$komitent_name = mb_convert_encoding($komitent_name,"UTF-8","HTML-ENTITIES");
								
								$q = "INSERT INTO listing_business VALUES(".$row["komitent_id"].",'$komitent_name','$mesto','".addslashes($adresa)."','$tel') "
									."ON DUPLICATE KEY UPDATE "
									."name='".prepForSQL($row["komitent_name"])."',"
									."mesto='$mesto',"
									."adresa='".prepForSQL($adresa)."', "
									."telefon='$tel'";
								if(!$db->alterTable($q)){
									echo mysql_error()."<br />";
								}
							}
						}
						
						$q = "SELECT * FROM listing_business ORDER BY name, mesto, adresa, telefon";
						$res = $db->select2($q);
						if ($res !== false) {
							$listingTXT="";
							$link = urlencode($letter);
							$this->assign("letter_link",$link);
							
							foreach ($res as $k=>$row){
								if (preg_match('/&#\d+;/',$row["name"])) {
									$row["name"] = mb_convert_encoding($row["name"],"UTF-8","HTML-ENTITIES");
								}
								$oglas = $this->getOglas($row["id"],$kampanja);
								file_put_contents("vojabusiness","\r\n\r\n".$row["name"].var_export($oglas,true),FILE_APPEND);
								//DaLiImaOglas($row["id"],$row["name"]);
								$oglasClass[$k] = $oglas===false?"":" class=\"oglas\"";
								$listingTXT .= "\n"
										    .$this->listingStyleDelimiter."s6".$this->listingStyleDelimiter.$row["name"]
										    ." - "
										    .$row["mesto"]
										    ."\n"
										    .$row["adresa"]
										    ."\t"
										    .$row["telefon"];
								if ($oglas) {
									//print_rarray($oglas);
									$listingTXT .= "\n".$this->listingStyleDelimiter."s4".$this->listingStyleDelimiter
												."(vidi oglas na strani"
												." ".implode(",",array_fill(0,count($oglas),"*"))
												.")";
								}
								$names[$k] = $komitent_name = $row["name"];
								$mestos[$k] = $row["mesto"];
								$adresas[$k] = $row["adresa"];
								$telefons[$k] = $row["telefon"];
							}
							$this->assign("name",$names);
							$this->assign("mesto",$mestos);
							$this->assign("adresa",$adresas);
							$this->assign("telefon",$telefons);
							$this->assign("oglas_class",$oglasClass);
							
							$listingTXT = trim($listingTXT);
							file_put_contents("business.txt",$listingTXT);
						}
					}
				}
			}
		}else{
			$this->assign("comment_start","<!--");
			$this->assign("comment_end","-->");
		}
		
		echo $this->parseTemplate("komitenti/listing_business.tpl");
	}
	
	//----------------------------------------------------------------------------
	//************************	SLANJE MATERIJALA	******************************
	//----------------------------------------------------------------------------
	
	function MaterijalSendView(){
		
		// get filter values
		$radid = getFromInput("f_radnik");
		$ugovor = readValFromInput("f_ugovor");
		$komitent = readValFromInput("f_komitent");
		$date_start = date2int(getFromInput("f_date_start"));
		$date_end = date2int(getFromInput("f_date_end"));
		$f_ishod = getFromInput("f_ishod");
		$f_ishod_time_start = date2int(getFromInput("f_ishod_time_start"));
		$f_ishod_time_end = date2int(getFromInput("f_ishod_time_end"));
		$page = getFromInput("page"); $page=$page>0?$page:1;
		
		$filter_query = "a=materijal"
					  ."&f_radnik=$radid"
					  ."&f_ugovor=$ugovor"
					  ."&f_komitent=$komitent"
					  ."&f_date_start=$date_start"
					  ."&f_date_end=$date_end"
					  ."&f_ishod=".$f_ishod
					  ."&f_ishod_time_start=".$f_ishod_time_start
					  ."&f_ishod_time_end=".$f_ishod_time_end;
		
		// assign filter values
		$polja = page::get_Radnici($radid);
			$this->assign("radnik_id",$polja["polje_id"]);
			$this->assign("radnik_ime",$polja["polje_ime"]);
			$this->assign("radnik_prezime",$polja["polje_prezime"]);
			$this->assign("radnik_selected",$polja["polje_selected"]);
		$this->assign("f_ugovor",$ugovor);
		$this->assign("f_komitent",$komitent);
		$this->assign("f_date_start",int2date($date_start));
		$this->assign("f_date_end",int2date($date_end));
		$this->assign("filter_query",$filter_query);
		$polja = $this->get_MaterijalSlanjeIshodi($f_ishod);
			$this->assign("ishod_id",$polja["polje_id"]);
			$this->assign("ishod_name",$polja["polje_ime"]);
			$this->assign("ishod_selected",$polja["polje_selected"]);
		$this->assign("f_ishod_time_start",int2date($f_ishod_time_start));
		$this->assign("f_ishod_time_end",int2date($f_ishod_time_end));
		
		
		$q_select = "SELECT ms.*,mst.name as tipname, msi.name as ishodname, r.radnik_ime, r.radnik_prezime, u.username ";
		$q_from = "FROM materijal_slanje ms, materijal_slanje_tipovi mst, materijal_slanje_ishodi msi, users u, radnici r";
		$q_where = "WHERE ms.type=mst.id AND ms.ishod=msi.id AND u.id=ms.user AND u.radnik_id=r.radnik_id";
		$q_order = "ORDER BY ms.time";
		$q_limit = "LIMIT ".(($page-1)*PAGE_LENGTH).",".PAGE_LENGTH;
		
		if ($radid>0) {
			$q_where .= " AND u.radnik_id=$radid";
		}
		if (strlen($ugovor)>0 || strlen($komitent)>0) {
			$q_from .= ", ugovori ug";
			$q_where .= " AND ug.id=ms.ugovor_id";
			if (strlen($ugovor)>0) {
				$qugoid = preg_match('/^\d+$/',$ugovor)?true:false;
				$q_where .= " AND ("
						   .($qugoid?"ug.id=$ugovor OR ":"")
						   ."ug.broj LIKE '%".prepForSQL($ugovor)."%'"
						   .")";
			}
			if (strlen($komitent)) {
				$qkomid = preg_match('/^\d+$/',$komitent)?true:false;
				$q_from .= ", komitenti k";
				$q_where .= " AND ug.komitent=k.komitent_id "
						   ." AND ("
						   .($qkomid?"k.komitent_id=$komitent OR ":"")
						   ."k.komitent_name LIKE '%".prepForSQL($komitent)."%' OR "
						   ."k.komitent_name1 LIKE '%".prepForSQL($komitent)."%')";
			}
		}
		if ($date_start>0 && $date_end>0 && $date_end>=$date_start) {
			$q_where .= " AND ms.time>=$date_start AND ms.time<=$date_end";
		}
		
		if ($f_ishod>0) {
			$q_where .= " AND ms.ishod=$f_ishod";
		}
		if ($f_ishod_time_start>0 && $f_ishod_time_end>0 && $f_ishod_time_end>=$f_ishod_time_start) {
			$q_where .= " AND ms.ishod_time>=$f_ishod_time_start AND ms.ishod_time<$f_ishod_time_end";
		}
		
		$q = "$q_select $q_from $q_where $q_order";
		$ukupno = $this->db->select2($q);
		$ukupno = $ukupno!==false?count($ukupno):0;
		
		$numpages = ceil($ukupno/PAGE_LENGTH);
		$polja = PageFilter($page,$numpages);
			$this->assign("page",$polja["page"]);
			$this->assign("page_current",$polja["current"]);
		
		$q .= " $q_limit";
		$res = $this->db->select2($q);
		if ($res !== false) {
			foreach ($res as $k=>$row){
				$ids[$k] = $row["id"];
				$username[$k] = $row["username"];
				$radnik[$k] = $row["radnik_ime"]." ".$row["radnik_prezime"];
				$ugovorid[$k] = $row["ugovor_id"];
				$ugovor[$k] = $this->db->getOne("SELECT broj FROM ugovori WHERE id=".$row["ugovor_id"]." LIMIT 1");
				
				$sql = "SELECT komitent_id, komitent_name "
					  ."FROM komitenti, ugovori "
					  ."WHERE komitenti.komitent_id=ugovori.komitent "
					  ."AND ugovori.id=".$row["ugovor_id"]." "
					  ."LIMIT 1";
				$kom = $this->db->getRow($sql,true);
				$komitent_id[$k] = $kom["komitent_id"];
				$komitent_name[$k] = $kom["komitent_name"];
				$tip_slanja[$k] = $row["tipname"];
				$datum[$k] = int2date($row["time"],"d.m.Y H:i");
				
				$ishod[$k] = $row["ishodname"];
				$ishod_time[$k] = $row["ishod_time"]>0?int2date($row["ishod_time"],"d.m.Y H:i"):"";
				
				$desc[$k] = nl2br($row["napomena"]);
			}
			$this->assign("id",$ids);
			$this->assign("username",$username);
			$this->assign("radnik",$radnik);
			$this->assign("ugovor",$ugovor);
			$this->assign("ugovorid",$ugovorid);
			$this->assign("komitent_id",$komitent_id);
			$this->assign("komitent_name",$komitent_name);
			$this->assign("tip_slanja",$tip_slanja);
			$this->assign("datum",$datum);
			$this->assign("ishod",$ishod);
			$this->assign("ishod_time",$ishod_time);
			$this->assign("opis",$desc);
		}else{
			$this->assign("comment_start","<!--");
			$this->assign("comment_end","-->Nema rezultata");
		}
			
		echo $this->parseTemplate("komitenti/materijalsend/view.tpl");
	}
	function MaterijalSendNew(){
		$polja = $this->get_MaterijalSlanjeTipovi();
			$this->assign("tip_slanja_id",$polja["polje_id"]);
			$this->assign("tip_slanja_name",$polja["polje_ime"]);
		$polja = $this->get_MaterijalSlanjeIshodi();
			$this->assign("ishod_id",$polja["polje_id"]);
			$this->assign("ishod_name",$polja["polje_ime"]);
		
		echo $this->parseTemplate("komitenti/materijalsend/new.tpl");
	}
	function MaterijalSendSave(){
		$user = $this->getUserId();
		$ugoid = getFromInput("ugovor_id");
		$type = getFromInput("tip_slanja");
		$ishod = getFromInput("ishod");
		$ishod_date = getFromInput("ishod_date");
		$ishod_hour = getFromInput("ishod_hour");
		$ishod_minute = getFromInput("ishod_minute");
		$desc = readValFromInput("opis");
		
		if ($ugoid<1) {
			die("Morate odabrati ugovor!");
		}
		
		$time = time();
		if (is_valid_date($ishod_date)) {
			list($ishod_day,$ishod_month,$ishod_year) = explode(".",$ishod_date);
			$ishod_time = makeUnixTime($ishod_hour,$ishod_minute,0,$ishod_month,$ishod_day,$ishod_year);
		}else{
			$ishod_time = 0;
		}
		$q = "INSERT INTO materijal_slanje(`user`,`ugovor_id`,`time`,`type`,`ishod`,`ishod_time`,`napomena`) "
			."VALUES($user,$ugoid,$time,$type,$ishod,$ishod_time,'".prepForSQL($desc)."')";
		
		if (@$this->db->alterTable($q)) {
			echo "Slanje materijala uspešno zabeleženo.";
		}else{
			echo "GREŠKA!\n\n".mysql_error();
		}
	}
	function MaterijalSendDelete(){
		$code = 0;
		$msg = "Zapis slanja materijala uspešno obrisan.";
		
		$id = getFromInput("id");
		$user = $this->getUserId();
		if ($id>0) {
			$ownerid = $this->db->getOne("SELECT user FROM materijal_slanje WHERE id=$id LIMIT 1");
			if ($ownerid==$user) {
				$q = "DELETE FROM materijal_slanje WHERE id=$id LIMIT 1";
				if (!@$this->db->alterTable($q)) {
					$code = 1;
					$msg = "Greška!\n\n".mysql_error();
				}
			}else{
				$code = 1;
				$msg = "Brisanje nije dozvoljeno.\nOdabrani zapis ne pripada Vama.";
			}
		}
		
		echo "$code{!}$msg";
	}
	
	//----------------------------------------------------------------------------
	
	
	function yapfox(){
		$mod = getFromInput("mod");
		switch ($mod){
			case "del":
				$this->yapfoxdel();
				$this->yapfoxshow();
				break;
			case "add":
				$this->yapfoxadd();
			default:
				$this->yapfoxshow();
				break;
		}
	}
	function yapfoxshow(){
		
		$page = ($p=getFromInput("page"))>0?$p:1;
		$filter_yap = getFromInput("fyap");
		$filter_fox = getFromInput("ffox");
		
		$start = ($page-1)*PAGE_LENGTH;
		
		
		$q = "SELECT yapfox.*,komitent_name FROM yapfox,komitenti WHERE yapfox.yap=komitenti.komitent_id";
		if(preg_match('/^\d+$/',$filter_yap)){
			$this->assign("filter_yap",$filter_yap);
			$q .= " AND yap=$filter_yap";
		}
		if(preg_match('/^\d+$/',$filter_fox)){
			$this->assign("filter_fox",$filter_fox);
			$q .= " AND fox=$filter_fox";
		}
		
		$q .= " ORDER BY yapfox.fox DESC";
		$all = $this->db->select1($q);
		$all = count($all);
		
		if ($all>1) {
			$numpages = bcdiv($all,PAGE_LENGTH,0);
			$rest = $all % $numpages;
			if($rest>0){
				$numpages++;
			}
		}else{
			$numpages=1;
		}
		
		for ($i=1; $i<=$numpages; $i++){
			$pages[] = $i;
			if($i==$page){
				$sel_page[] = "current";
			}else{
				$sel_page[] = "";
			}
		}
		$this->assign("page",$pages);
		$this->assign("current_page",$sel_page);
		
		$q .= " LIMIT $start,".PAGE_LENGTH;
		$res = $this->db->select2($q);
		
		if($res !== false){
			foreach ($res as $k=>$row){
				$red[] = $start+1+$k;
				$yap[] = $row["yap"];
				$fox[] = $row["fox"];
				$name[] = $row["komitent_name"];
			}
			$this->assign("red",$red);
			$this->assign("yap",$yap);
			$this->assign("fox",$fox);
			$this->assign("name",$name);
		}
		echo $this->parseTemplate("komitenti/yapfox.tpl");
	}
	function yapfoxadd(){
		$yap = getFromInput("yap");
		$fox = getFromInput("fox");
		
		$user = $_COOKIE["ypu"];
		$time = time();
		
		$q = "INSERT INTO yapfox VALUES($yap,$fox,$time,$user)";
		if($this->db->alterTable($q)){
			echo "Unos izvršen.";
		}else{
			echo "Greška!<br />".mysql_error();
		}
	}
	function yapfoxdel(){
		$yap = getFromInput("yap");
		$fox = getFromInput("fox");
		$q = "DELETE FROM yapfox WHERE yap=$yap AND fox=$fox";
		if($this->db->alterTable($q)){
			echo "Brisanje izvršeno.";
		}else{
			echo "Greška!<br />".mysql_error();
		}
	}
	
	function yapyap(){
		$page = ($pg=getFromInput("page"))>0?$pg:1;
		$start = ($page-1)*PAGE_LENGTH;
		
		$parent = getFromInput("filter_parent");
		$parent_name = readValFromInput("filter_parent_name");
		$child = getFromInput("filter_child");
		$child_name = readValFromInput("filter_child_name");
		
		$this->assign("filter_parent",$parent);
		$this->assign("filter_parent_name",$parent_name);
		$this->assign("filter_child",$child);
		$this->assign("filter_child_name",$child_name);
		
		$q = "SELECT * FROM komitenti_komitenti WHERE 1 ";
		if ($parent>0) {
			$q .= "AND parent=$parent ";
		}
		if ($child>0) {
			$q .= "AND child=$child ";
		}
		$ukupno = count($this->db->select1($q));
		
		$q .= "LIMIT $start,".PAGE_LENGTH;
		
		$numpages = bcdiv($ukupno,PAGE_LENGTH,0);
		if ($ukupno % PAGE_LENGTH) {
			$numpages++;
		}
		
		for ($i=0; $i<$numpages; $i++){
			$p[$i] = $i+1;
			if (($i+1)==$page) {
				$c[$i] = " id=\"current\"";
			}else{
				$c[$i] = "";
			}
		}
		$this->assign("current_page",$page);
		$this->assign("page",$p);
		$this->assign("current",$c);
		
		$res = $this->db->select2($q);
		if ($res !== false) {
			foreach ($res as $row){
				$kom1id[] = $row["parent"];
				$kom1name[] = $this->db->getOne("SELECT komitent_name FROM komitenti WHERE komitent_id=".$row["parent"]." LIMIT 1");
				$kom2id[] = $row["child"];
				$kom2name[] = $this->db->getOne("SELECT komitent_name FROM komitenti WHERE komitent_id=".$row["child"]." LIMIT 1");
			}
			$this->assign("komitent1_id",$kom1id);
			$this->assign("komitent1_name",$kom1name);
			$this->assign("komitent2_id",$kom2id);
			$this->assign("komitent2_name",$kom2name);
		}else{
			$this->assign("comment_start","<!--");
			$this->assign("comment_end","-->Nema rezultata");
		}
		
		
		echo $this->parseTemplate("komitenti/yapyap.tpl");
	}
	function yapyapDelete(){
		$parent = getFromInput("parent");
		$child = getFromInput("child");
		$q = "DELETE FROM komitenti_komitenti WHERE parent=$parent AND child=$child";
		if ($this->db->alterTable($q)) {
			echo "0{!}Brisanje izvršeno.";
		}else{
			echo "1{!}".mysql_error();
		}
	}
	function yapyapAdd(){
		$parent = getFromInput("parent");
		$child = getFromInput("child");
		$ima = $this->db->getOne("SELECT 1 FROM komitenti_komitenti WHERE (parent=$parent AND child=$child) OR (parent=$child AND child=$parent)");
		$code=1;
		$msg = "Unos izvršen.";
		if($ima){
			$code = "0";
			$msg = "Veza već postoji";
		}else{
			$q = "INSERT INTO komitenti_komitenti VALUES($parent,$child)";
			if (!$this->db->alterTable($q)) {
				$code = "0";
				$msg = mysql_error();
			}
		}
		echo "$code{!}$msg";
	}
	
	function getSettings($kampanja){
		$q = "SELECT * FROM listing_settings WHERE kampanja=$kampanja ORDER BY name";
		$setts = $this->db->select2($q);
		$settings = array();
		if($setts===false){
			return false;
		}else{
			foreach ($setts as $set){
				$settings[$set["name"]]=$set["value"];
			}
		}
		return $settings;
	}
	
	function sortRes($res,$sort="komitent_name"){
		$obj = array();
		foreach ($res as $k=>$v){
			foreach ($v as $m=>$n){
				$obj[$m][$k] = $n;
			}
		}
		if(isset($obj[$sort])){
			natsort($obj[$sort]);
			$ret = array();
			$names = array_keys($obj);
			$i=0;
			foreach ($obj[$sort] as $k=>$v){
				foreach ($names as $n){
					$ret[$i][$n] = $obj[$n][$k];
				}
				$i++;
			}
			return $ret;
		}else{
			return $res;
		}
	}
	
	//-------------------------------------------------------------------------
	
	function get_Telefoni($komid,$delid=null,$adresa=null,$fax=null){
		$q = "SELECT * FROM komitenti_telefoni WHERE kom_id=$komid";
		if($delid !== null){
			$q .= " AND del_id=$delid";
		}
		if($adresa !== null){
			$q .= " AND adresa=$adresa";
		}
		if($fax !== null){
			$q .= " AND fax=$fax";
		}
		$q .= " ORDER BY `order`, telefon, del_id";
		$res = $this->db->select2($q);
		if($res){
			return $res;
		}else{
			return false;
		}
	}
	function generateNewDelHTML($delid,$index=1){
		$this->assign("dels_data_count",$delid);
		$this->assign("dels_data_count1",$index);
		$this->assign("komdel_delid",$delid);
		
		$this->assignAdresaObjects();
		
		// platne kartice
		$sve_kartice = $this->db->select2("SELECT * FROM kartice ORDER BY card_name");
		foreach ($sve_kartice as $card){
			$cids[] = $card["card_id"];
			$cnames[] = $card["card_name"];
		}
		$this->assign("card_id",$cids);
		$this->assign("card_name",$cnames);
		
		// generate del_data
		//$this->assign();
		$this->assign("del_data_tpl",$this->parseTemplate("komitenti/view/del_data_template.tpl"));
		
		// throw whole template
		echo $this->parseTemplate("komitenti/view/del_template.tpl");
	}
	function generateNewDelDataHTML($delid,$index=1){
		
		$this->assign("dels_data_count",$delid);
		$this->assign("dels_data_count1",$index);
		
		$this->assignAdresaObjects();
		
		// platne kartice
		$sve_kartice = $this->db->select2("SELECT * FROM kartice ORDER BY card_name");
		foreach ($sve_kartice as $card){
			$cids[] = $card["card_id"];
			$cnames[] = $card["card_name"];
		}
		$this->assign("card_id",$cids);
		$this->assign("card_name",$cnames);
		
		// generate del_data
		//$this->assign();
		echo $this->parseTemplate("komitenti/view/del_data_template.tpl");
	}
	function assignAdresaObjects(){
		// ADRESA
		$polja = $this->get_Regioni();
			$this->assign("region_id",$polja["polje_id"]);
			$this->assign("region_name",$polja["polje_ime"]);
		$polja = $this->get_Opstine();
			$this->assign("opstina_id",$polja["polje_id"]);
			$this->assign("opstina_name",$polja["polje_ime"]);
			$this->assign("opstina_parent",$polja["polje_parent"]);
		$polja = $this->get_Mesta();
			$this->assign("mesto_id",$polja["polje_id"]);
			$this->assign("mesto_name",$polja["polje_ime"]);
			$this->assign("mesto_parent",$polja["polje_parent"]);
			$this->assign("mesto_ptt",$polja["polje_ptt"]);
		$polja = $this->get_LokOpstine();
			$this->assign("lok_opstina_id",$polja["polje_id"]);
			$this->assign("lok_opstina_name",$polja["polje_ime"]);
			$this->assign("lok_opstina_parent",$polja["polje_parent"]);
			$this->assign("lok_opstina_ptt",$polja["polje_ptt"]);
		$polja = $this->get_Naselja();
			$this->assign("naselje_id",$polja["polje_id"]);
			$this->assign("naselje_name",$polja["polje_ime"]);
			$this->assign("naselje_parent",$polja["polje_parent"]);
			$this->assign("naselje_ptt",$polja["polje_ptt"]);
	}
	function getLastUser($id){
		
		/*$logdir = "logs/";
		$dir = opendir($logdir);
		$files = array();
		
		$userid=false;
		$lastdate=-1;
		
		while ($f = readdir($dir)) {
			if (!preg_match('/\.{1,2}/',$f)) {
				$file = file($logdir.$f);
				$file = array_map("trim",$file);
				
				foreach ($file as $line){
					$tmp = explode("\t",$line);
					if ($tmp[6]==$id) {
						if ($tmp[5] == "komitent_id") {
							if ($tmp[1]>$lastdate) {
								$userid=$tmp[0];
								$lastdate=$tmp[1];
							}
						}
					}
				}
			}
		}*/
		$q = "SELECT user, time, state FROM log WHERE `table`='komitenti' AND `attribute`='komitent_id' AND `value`='$id' ORDER BY time DESC LIMIT 1";
		$res = $this->db->select2($q);
		
		//echo $q;
		if ($res !== false) {
			$userid = $res[0]["user"];
			$lastdate = $res[0]["time"];
			$state = $res[0]["state"];
			
			$q = "SELECT radnik_ime, radnik_prezime FROM users, radnici WHERE users.radnik_id=radnici.radnik_id AND users.id=$userid LIMIT 1";
			$res = $this->db->getRow($q);
			$ret["ime"]		= $res[0];
			$ret["prezime"]	= $res[1];
			$ret["time"]	= $lastdate;
			$ret["state"]	= $state;
			
			return $ret;
		}else{
			return false;
		}
	}
	function getLIDS($ltip,$lid){
		$ret = array();
		$ltip = intval($ltip);
		switch ($ltip){
			case 2:
				$nas = $this->db->select1("SELECT lid FROM lokacije WHERE lok_tip=3 AND lok_parent=$lid");
				if ($nas !== false) {
					foreach ($nas as $nid){
						$ret[] = $nid[0];
					}
				}
				break;
			case 1:
				$lops = $this->db->select1("SELECT lid FROM lokacije WHERE lok_tip=2 AND lok_parent=$lid");
				if($lops !== false){
					foreach ($lops as $loid){
						$ret[] = $loid[0];
						$nas = $this->db->select1("SELECT lid FROM lokacije WHERE lok_tip=3 AND lok_parent=".$loid[0]);
						if ($nas !== false) {
							foreach ($nas as $nid){
								$ret[] = $nid[0];
							}
						}
					}
				}
				break;
		}
		return $ret;
	}
	function get_MaterijalSlanjeTipovi($tip=null){
		$ret = array();
		$res = $this->db->select2("SELECT * FROM materijal_slanje_tipovi ORDER BY name");
		if ($res !== false) {
			foreach ($res as $k=>$v){
				$ret["polje_id"][$k] = $v["id"];
				$ret["polje_ime"][$k] = $v["name"];
				$ret["polje_selected"][$k] = $v["id"]==$tip?" selected":"";
			}
		}
		return $ret;
	}
	
	function get_MaterijalSlanjeIshodi($ishod=null){
		$ret = array();
		$res = $this->db->select2("SELECT * FROM materijal_slanje_ishodi ORDER BY name");
		if ($res !== false) {
			foreach ($res as $k=>$v){
				$ret["polje_id"][$k] = $v["id"];
				$ret["polje_ime"][$k] = $v["name"];
				$ret["polje_selected"][$k] = $v["id"]==$ishod?" selected":"";
			}
		}
		return $ret;
	}
}
?>